| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- package jobs
- import (
- "IotAdmin/app/schedule/models"
- "IotAdmin/core/sdk"
- "IotAdmin/core/sdk/pkg/cronjob"
- "fmt"
- "time"
- "gorm.io/gorm"
- )
- var (
- // jobList 定义的job
- jobList map[string]JobExec
- )
- // InitJob 初始化job
- func InitJob() {
- initJobList()
- Setup(sdk.Runtime.GetDb())
- }
- // 需要将定义的struct 添加到字典中;
- // 字典 key 可以配置到 自动任务 调用目标 中;
- func initJobList() {
- jobList = map[string]JobExec{
- "CleanLog": &CleanLog{},
- "ExamplesOne": &ExamplesOne{},
- // ...
- }
- }
- // Setup 初始化
- func Setup(dbs map[string]*gorm.DB) {
- fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore Starting...")
- for k, db := range dbs {
- sdk.Runtime.SetCrontab(k, cronjob.NewWithSeconds())
- setup(k, db)
- }
- }
- func setup(key string, db *gorm.DB) {
- crontab := sdk.Runtime.GetCrontabKey(key)
- sysJob := models.SysJob{}
- jobList := make([]models.SysJob, 0)
- err := sysJob.GetList(db, &jobList)
- if err != nil {
- fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore init error", err)
- }
- if len(jobList) == 0 {
- fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore total:0")
- }
- _, err = sysJob.RemoveAllEntryID(db)
- if err != nil {
- fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore remove entry_id error", err)
- }
- for i := 0; i < len(jobList); i++ {
- if jobList[i].JobType == 1 {
- j := &HttpJob{}
- j.InvokeTarget = jobList[i].InvokeTarget
- j.CronExpression = jobList[i].CronExpression
- j.JobId = jobList[i].JobId
- j.Name = jobList[i].JobName
- sysJob.EntryId, err = AddJob(crontab, j)
- } else if jobList[i].JobType == 2 {
- j := &ExecJob{}
- j.InvokeTarget = jobList[i].InvokeTarget
- j.CronExpression = jobList[i].CronExpression
- j.JobId = jobList[i].JobId
- j.Name = jobList[i].JobName
- j.Args = jobList[i].Args
- sysJob.EntryId, err = AddJob(crontab, j)
- }
- err = sysJob.Update(db, jobList[i].JobId)
- }
- // 其中任务
- crontab.Start()
- fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore start success.")
- // 关闭任务
- defer crontab.Stop()
- select {}
- }
- // GetJobKeys 获取job key列表
- func GetJobKeys() []string {
- var list []string
- for k := range jobList {
- list = append(list, k)
- }
- return list
- }
|