github.com/v2fly/v2ray-core/v4@v4.45.2/common/task/periodic_test.go (about)

     1  package task_test
     2  
     3  import (
     4  	"sync/atomic"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/v2fly/v2ray-core/v4/common"
     9  	. "github.com/v2fly/v2ray-core/v4/common/task"
    10  )
    11  
    12  func TestPeriodicTaskStop(t *testing.T) {
    13  	var value uint64
    14  	task := &Periodic{
    15  		Interval: time.Second * 2,
    16  		Execute: func() error {
    17  			atomic.AddUint64(&value, 1)
    18  			return nil
    19  		},
    20  	}
    21  	common.Must(task.Start())
    22  	time.Sleep(time.Second * 5)
    23  	common.Must(task.Close())
    24  	value1 := atomic.LoadUint64(&value)
    25  	if value1 != 3 {
    26  		t.Fatal("expected 3, but got ", value1)
    27  	}
    28  
    29  	time.Sleep(time.Second * 4)
    30  	value2 := atomic.LoadUint64(&value)
    31  	if value2 != 3 {
    32  		t.Fatal("expected 3, but got ", value2)
    33  	}
    34  
    35  	common.Must(task.Start())
    36  	time.Sleep(time.Second * 3)
    37  	value3 := atomic.LoadUint64(&value)
    38  	if value3 != 5 {
    39  		t.Fatal("Expected 5, but ", value3)
    40  	}
    41  	common.Must(task.Close())
    42  }