gitee.com/quant1x/engine@v1.8.4/services/scheduler.go (about) 1 package services 2 3 import ( 4 "errors" 5 "fmt" 6 "gitee.com/quant1x/engine/config" 7 "gitee.com/quant1x/gox/coroutine" 8 "gitee.com/quant1x/gox/cron" 9 "gitee.com/quant1x/gox/logger" 10 "gitee.com/quant1x/gox/runtime" 11 "strings" 12 "sync" 13 ) 14 15 // Task 定时任务 16 // 17 // 默认每10秒检测1次 18 // 排名不分先后 19 type Task struct { 20 name string // 任务名称 21 spec string // 触发条件 22 Service func() // 任务函数 23 } 24 25 var ( 26 ErrAlreadyExists = errors.New("the job already exists") // 任务已经存在 27 ErrForbidden = errors.New("the job was forbidden") // 任务被禁止 28 ) 29 30 var ( 31 jobMutex sync.Mutex 32 mapJobs = map[string]Task{} 33 crontab = cron.New() 34 ) 35 36 // Register 注册定时任务 37 func Register(name, spec string, callback func()) error { 38 jobMutex.Lock() 39 defer jobMutex.Unlock() 40 _, ok := mapJobs[name] 41 if ok { 42 return ErrAlreadyExists 43 } 44 if len(spec) == 0 { 45 spec = CronDefaultInterval 46 } 47 enable := true 48 jobParam := config.GetJobParameter(name) 49 if jobParam != nil { 50 enable = jobParam.Enable 51 trigger := strings.TrimSpace(jobParam.Trigger) 52 if len(trigger) > 0 { 53 spec = trigger 54 } 55 } 56 if !enable { 57 // 配置禁止任务, 不能返回错误 58 return nil 59 } 60 job := Task{name: name, spec: spec, Service: callback} 61 mapJobs[job.name] = job 62 return nil 63 } 64 65 // DaemonService 守护进程服务入口 66 func DaemonService() { 67 jobMutex.Lock() 68 // 启动服务 69 logger.Infof("启动定时任务列表") 70 crontab.Start() 71 // 输出2个空白行 72 fmt.Printf("%s", strings.Repeat("\n", 2)) 73 for _, v := range mapJobs { 74 message := fmt.Sprintf("Service: %s, Interval: %s, ", v.name, v.spec) 75 logger.Info(message) 76 _, err := crontab.AddJobWithSkipIfStillRunning(v.spec, v.Service) 77 if err != nil { 78 logger.Infof(message+"failed, err: %s", err.Error()) 79 } else { 80 logger.Infof(message + "success") 81 } 82 } 83 jobMutex.Unlock() 84 // 等待结束 85 coroutine.WaitForShutdown() 86 // 关闭任务调度 87 crontab.Stop() 88 } 89 90 // PrintJobList 输出定时任务列表 91 func PrintJobList() { 92 for _, v := range mapJobs { 93 spec := v.spec 94 message := fmt.Sprintf("Service: %s, Interval: %s, method: %s", v.name, spec, runtime.FuncName(v.Service)) 95 fmt.Println(message) 96 } 97 }