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.

86 lines
2.3 KiB

  1. /**
  2. * @Author: Aceld
  3. * @Date: 2019/5/7 18:00
  4. * @Mail: danbing.at@gmail.com
  5. *
  6. * 针对 timer_wheel.go 时间轮api 做单元测试, 主要测试时间轮运转功能
  7. * 依赖模块 delayFunc.go timer.go
  8. */
  9. package ztimer
  10. import (
  11. "fmt"
  12. "testing"
  13. "time"
  14. )
  15. func TestTimerWheel(t *testing.T) {
  16. //创建秒级时间轮
  17. second_tw := NewTimeWheel(SECOND_NAME, SECOND_INTERVAL, SECOND_SCALES, TIMERS_MAX_CAP)
  18. //创建分钟级时间轮
  19. minute_tw := NewTimeWheel(MINUTE_NAME, MINUTE_INTERVAL, MINUTE_SCALES, TIMERS_MAX_CAP)
  20. //创建小时级时间轮
  21. hour_tw := NewTimeWheel(HOUR_NAME, HOUR_INTERVAL, HOUR_SCALES, TIMERS_MAX_CAP)
  22. //将分层时间轮做关联
  23. hour_tw.AddTimeWheel(minute_tw)
  24. minute_tw.AddTimeWheel(second_tw)
  25. fmt.Println("init timewheels done!")
  26. //===== > 以上为初始化分层时间轮 <====
  27. //给时间轮添加定时器
  28. timer1 := NewTimerAfter(NewDelayFunc(myFunc, []interface{}{1, 10}), 10*time.Second)
  29. _ = hour_tw.AddTimer(1, timer1)
  30. fmt.Println("add timer 1 done!")
  31. //给时间轮添加定时器
  32. timer2 := NewTimerAfter(NewDelayFunc(myFunc, []interface{}{2, 20}), 20*time.Second)
  33. _ = hour_tw.AddTimer(2, timer2)
  34. fmt.Println("add timer 2 done!")
  35. //给时间轮添加定时器
  36. timer3 := NewTimerAfter(NewDelayFunc(myFunc, []interface{}{3, 30}), 30*time.Second)
  37. _ = hour_tw.AddTimer(3, timer3)
  38. fmt.Println("add timer 3 done!")
  39. //给时间轮添加定时器
  40. timer4 := NewTimerAfter(NewDelayFunc(myFunc, []interface{}{4, 40}), 40*time.Second)
  41. _ = hour_tw.AddTimer(4, timer4)
  42. fmt.Println("add timer 4 done!")
  43. //给时间轮添加定时器
  44. timer5 := NewTimerAfter(NewDelayFunc(myFunc, []interface{}{5, 50}), 50*time.Second)
  45. _ = hour_tw.AddTimer(5, timer5)
  46. fmt.Println("add timer 5 done!")
  47. //时间轮运行
  48. second_tw.Run()
  49. minute_tw.Run()
  50. hour_tw.Run()
  51. fmt.Println("timewheels are run!")
  52. go func() {
  53. n := 0.0
  54. for {
  55. fmt.Println("tick...", n)
  56. //取出近1ms的超时定时器有哪些
  57. timers := hour_tw.GetTimerWithIn(1000 * time.Millisecond)
  58. for _, timer := range timers {
  59. //调用定时器方法
  60. timer.delayFunc.Call()
  61. }
  62. time.Sleep(500 * time.Millisecond)
  63. n += 0.5
  64. }
  65. }()
  66. //主进程等待其他go,由于Run()方法是用一个新的go承载延迟方法,这里不能用waitGroup
  67. time.Sleep(10 * time.Minute)
  68. }