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.

109 lines
2.3 KiB

  1. package timer
  2. import (
  3. "sync"
  4. "github.com/robfig/cron/v3"
  5. )
  6. type Timer interface {
  7. AddTaskByFunc(taskName string, spec string, task func()) (cron.EntryID, error)
  8. AddTaskByJob(taskName string, spec string, job interface{ Run() }) (cron.EntryID, error)
  9. FindCron(taskName string) (*cron.Cron, bool)
  10. StartTask(taskName string)
  11. StopTask(taskName string)
  12. Remove(taskName string, id int)
  13. Clear(taskName string)
  14. Close()
  15. }
  16. // timer 定时任务管理
  17. type timer struct {
  18. taskList map[string]*cron.Cron
  19. sync.Mutex
  20. }
  21. // AddTaskByFunc 通过函数的方法添加任务
  22. func (t *timer) AddTaskByFunc(taskName string, spec string, task func()) (cron.EntryID, error) {
  23. t.Lock()
  24. defer t.Unlock()
  25. if _, ok := t.taskList[taskName]; !ok {
  26. t.taskList[taskName] = cron.New()
  27. }
  28. id, err := t.taskList[taskName].AddFunc(spec, task)
  29. t.taskList[taskName].Start()
  30. return id, err
  31. }
  32. // AddTaskByJob 通过接口的方法添加任务
  33. func (t *timer) AddTaskByJob(taskName string, spec string, job interface{ Run() }) (cron.EntryID, error) {
  34. t.Lock()
  35. defer t.Unlock()
  36. if _, ok := t.taskList[taskName]; !ok {
  37. t.taskList[taskName] = cron.New()
  38. }
  39. id, err := t.taskList[taskName].AddJob(spec, job)
  40. t.taskList[taskName].Start()
  41. return id, err
  42. }
  43. // FindCron 获取对应taskName的cron 可能会为空
  44. func (t *timer) FindCron(taskName string) (*cron.Cron, bool) {
  45. t.Lock()
  46. defer t.Unlock()
  47. v, ok := t.taskList[taskName]
  48. return v, ok
  49. }
  50. // StartTask 开始任务
  51. func (t *timer) StartTask(taskName string) {
  52. t.Lock()
  53. defer t.Unlock()
  54. if v, ok := t.taskList[taskName]; ok {
  55. v.Start()
  56. }
  57. return
  58. }
  59. // StopTask 停止任务
  60. func (t *timer) StopTask(taskName string) {
  61. t.Lock()
  62. defer t.Unlock()
  63. if v, ok := t.taskList[taskName]; ok {
  64. v.Stop()
  65. }
  66. return
  67. }
  68. // Remove 从taskName 删除指定任务
  69. func (t *timer) Remove(taskName string, id int) {
  70. t.Lock()
  71. defer t.Unlock()
  72. if v, ok := t.taskList[taskName]; ok {
  73. v.Remove(cron.EntryID(id))
  74. }
  75. return
  76. }
  77. // Clear 清除任务
  78. func (t *timer) Clear(taskName string) {
  79. t.Lock()
  80. defer t.Unlock()
  81. if v, ok := t.taskList[taskName]; ok {
  82. v.Stop()
  83. delete(t.taskList, taskName)
  84. }
  85. }
  86. // Close 释放资源
  87. func (t *timer) Close() {
  88. t.Lock()
  89. defer t.Unlock()
  90. for _, v := range t.taskList {
  91. v.Stop()
  92. }
  93. }
  94. func NewTimerTask() Timer {
  95. return &timer{taskList: make(map[string]*cron.Cron)}
  96. }