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.

106 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. }
  58. // StopTask 停止任务
  59. func (t *timer) StopTask(taskName string) {
  60. t.Lock()
  61. defer t.Unlock()
  62. if v, ok := t.taskList[taskName]; ok {
  63. v.Stop()
  64. }
  65. }
  66. // Remove 从taskName 删除指定任务
  67. func (t *timer) Remove(taskName string, id int) {
  68. t.Lock()
  69. defer t.Unlock()
  70. if v, ok := t.taskList[taskName]; ok {
  71. v.Remove(cron.EntryID(id))
  72. }
  73. }
  74. // Clear 清除任务
  75. func (t *timer) Clear(taskName string) {
  76. t.Lock()
  77. defer t.Unlock()
  78. if v, ok := t.taskList[taskName]; ok {
  79. v.Stop()
  80. delete(t.taskList, taskName)
  81. }
  82. }
  83. // Close 释放资源
  84. func (t *timer) Close() {
  85. t.Lock()
  86. defer t.Unlock()
  87. for _, v := range t.taskList {
  88. v.Stop()
  89. }
  90. }
  91. func NewTimerTask() Timer {
  92. return &timer{taskList: make(map[string]*cron.Cron)}
  93. }