periodic_test.go 806 B

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