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.

80 lines
1.8 KiB

  1. /**
  2. * @Author: Aceld(刘丹冰)
  3. * @Date: 2019/5/9 10:14
  4. * @Mail: danbing.at@gmail.com
  5. *
  6. * 时间轮定时器调度器单元测试
  7. */
  8. package ztimer
  9. import (
  10. "fmt"
  11. "github.com/aceld/zinx/zlog"
  12. "log"
  13. "testing"
  14. "time"
  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, _ := Scheduler.CreateTimerAfter(f1, time.Duration(3)*time.Second)
  64. timerId2, _ := Scheduler.CreateTimerAfter(f2, time.Duration(5)*time.Second)
  65. log.Printf("timerId1=%d ,timerId2=%d\n", timerId1, timerId2)
  66. Scheduler.CancelTimer(timerId1) //删除timerId1
  67. //阻塞等待
  68. select {}
  69. }