github.com/coyove/common@v0.0.0-20240403014525-f70e643f9de8/sched/sched_test.go (about)

     1  package sched
     2  
     3  import (
     4  	"fmt"
     5  	"math/rand"
     6  	"sync/atomic"
     7  	"testing"
     8  	"time"
     9  )
    10  
    11  func TestSched(t *testing.T) {
    12  	rand.Seed(time.Now().Unix())
    13  
    14  	var x atomic.Int64
    15  
    16  	m := NewGroup(func(data []any) {
    17  		// fmt.Println(len(data))
    18  		for _, d := range data {
    19  			x.Add(int64(d.(int)))
    20  		}
    21  	})
    22  
    23  	const N = 1e6
    24  	ref := map[int]Key{}
    25  	for i := 0; i < N; i++ {
    26  		d := time.Second + time.Duration(rand.Intn(2000))*time.Millisecond
    27  		k := m.Schedule(d, i)
    28  		ref[i] = k
    29  	}
    30  
    31  	c := 0
    32  	deletes := 0
    33  	for i, key := range ref {
    34  		m.Cancel(key)
    35  		deletes += i
    36  		if c++; c > 10 {
    37  			break
    38  		}
    39  	}
    40  
    41  	time.Sleep(time.Second * 4)
    42  	fmt.Println(x.Load(), N*(N-1)/2-deletes)
    43  
    44  	{
    45  		m := NewGroup(func(data []any) {
    46  			fmt.Println(data)
    47  			if len(data) != 1 || data[0] != 2 {
    48  				t.Fatal(data)
    49  			}
    50  		})
    51  		a := m.Schedule(time.Second+1, 1)
    52  		m.Schedule(time.Second+2, 2)
    53  		m.Cancel(a)
    54  	}
    55  
    56  	select {}
    57  }