You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.1 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package ztimer
  2. /**
  3. * @Author: Aceld(刘丹冰)
  4. * @Date: 2019/5/9 10:14
  5. * @Mail: danbing.at@gmail.com
  6. *
  7. * 时间轮定时器调度器单元测试
  8. */
  9. import (
  10. "fmt"
  11. "log"
  12. "testing"
  13. "time"
  14. "github.com/aceld/zinx/zlog"
  15. )
  16. //触发函数
  17. func foo(args ...interface{}) {
  18. fmt.Printf("I am No. %d function, delay %d ms\n", args[0].(int), args[1].(int))
  19. }
  20. //手动创建调度器运转时间轮
  21. func TestNewTimerScheduler(t *testing.T) {
  22. timerScheduler := NewTimerScheduler()
  23. timerScheduler.Start()
  24. //在scheduler中添加timer
  25. for i := 1; i < 2000; i++ {
  26. f := NewDelayFunc(foo, []interface{}{i, i * 3})
  27. tID, err := timerScheduler.CreateTimerAfter(f, time.Duration(3*i)*time.Millisecond)
  28. if err != nil {
  29. zlog.Error("create timer error", tID, err)
  30. break
  31. }
  32. }
  33. //执行调度器触发函数
  34. go func() {
  35. delayFuncChan := timerScheduler.GetTriggerChan()
  36. for df := range delayFuncChan {
  37. df.Call()
  38. }
  39. }()
  40. //阻塞等待
  41. select {}
  42. }
  43. //采用自动调度器运转时间轮
  44. func TestNewAutoExecTimerScheduler(t *testing.T) {
  45. autoTS := NewAutoExecTimerScheduler()
  46. //给调度器添加Timer
  47. for i := 0; i < 2000; i++ {
  48. f := NewDelayFunc(foo, []interface{}{i, i * 3})
  49. tID, err := autoTS.CreateTimerAfter(f, time.Duration(3*i)*time.Millisecond)
  50. if err != nil {
  51. zlog.Error("create timer error", tID, err)
  52. break
  53. }
  54. }
  55. //阻塞等待
  56. select {}
  57. }
  58. //测试取消一个定时器
  59. func TestCancelTimerScheduler(t *testing.T) {
  60. Scheduler := NewAutoExecTimerScheduler()
  61. f1 := NewDelayFunc(foo, []interface{}{3, 3})
  62. f2 := NewDelayFunc(foo, []interface{}{5, 5})
  63. timerID1, err := Scheduler.CreateTimerAfter(f1, time.Duration(3)*time.Second)
  64. if nil != err {
  65. t.Log("Scheduler.CreateTimerAfter(f1, time.Duration(3)*time.Second)", "err:", err)
  66. }
  67. timerID2, err := Scheduler.CreateTimerAfter(f2, time.Duration(5)*time.Second)
  68. if nil != err {
  69. t.Log("Scheduler.CreateTimerAfter(f1, time.Duration(3)*time.Second)", "err:", err)
  70. }
  71. log.Printf("timerID1=%d ,timerID2=%d\n", timerID1, timerID2)
  72. Scheduler.CancelTimer(timerID1) //删除timerID1
  73. //阻塞等待
  74. select {}
  75. }