cron.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package mhayaCron
  2. import (
  3. "fmt"
  4. "time"
  5. clog "github.com/mhaya/logger"
  6. "github.com/robfig/cron/v3"
  7. )
  8. var _cron = cron.New(
  9. cron.WithSeconds(),
  10. cron.WithChain(cron.Recover(&CronLogger{})),
  11. )
  12. type CronLogger struct {
  13. }
  14. func (CronLogger) Info(msg string, keysAndValues ...interface{}) {
  15. clog.Infow(msg, keysAndValues...)
  16. }
  17. func (CronLogger) Error(err error, _ string, _ ...interface{}) {
  18. clog.Error(err)
  19. }
  20. func Init(opts ...cron.Option) {
  21. if len(opts) < 1 {
  22. opts = append(opts, cron.WithSeconds())
  23. opts = append(opts, cron.WithChain(cron.Recover(&CronLogger{})))
  24. }
  25. _cron = cron.New(opts...)
  26. }
  27. func AddFunc(spec string, cmd func()) (cron.EntryID, error) {
  28. return _cron.AddJob(spec, cron.FuncJob(cmd))
  29. }
  30. // AddEveryDayFunc 每天的x时x分x秒执行一次(每天1次)
  31. func AddEveryDayFunc(cmd func(), hour, minutes, seconds int) (cron.EntryID, error) {
  32. spec := fmt.Sprintf("%d %d %d * * ?", seconds, minutes, hour)
  33. return _cron.AddFunc(spec, cmd)
  34. }
  35. // AddEveryHourFunc 每小时的x分x秒执行一次(每天24次)
  36. func AddEveryHourFunc(cmd func(), minute, second int) (cron.EntryID, error) {
  37. spec := fmt.Sprintf("%d %d * * * ?", second, minute)
  38. return _cron.AddFunc(spec, cmd)
  39. }
  40. // AddDurationFunc 每间隔x秒执行一次
  41. func AddDurationFunc(cmd func(), duration time.Duration) (cron.EntryID, error) {
  42. spec := fmt.Sprintf("@every %ds", int(duration.Seconds()))
  43. clog.Debug(spec)
  44. return _cron.AddFunc(spec, cmd)
  45. }
  46. func AddJob(spec string, cmd cron.Job) (cron.EntryID, error) {
  47. return _cron.AddJob(spec, cmd)
  48. }
  49. func Schedule(schedule cron.Schedule, cmd cron.Job) cron.EntryID {
  50. return _cron.Schedule(schedule, cmd)
  51. }
  52. func Entries() []cron.Entry {
  53. return _cron.Entries()
  54. }
  55. func Location() *time.Location {
  56. return _cron.Location()
  57. }
  58. func Entry(id cron.EntryID) cron.Entry {
  59. return _cron.Entry(id)
  60. }
  61. func Remove(id cron.EntryID) {
  62. _cron.Remove(id)
  63. }
  64. func Start() {
  65. _cron.Start()
  66. }
  67. func Run() {
  68. _cron.Run()
  69. }
  70. func Stop() {
  71. _cron.Stop()
  72. }