init.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package jobs
  2. import (
  3. "IotAdmin/app/schedule/models"
  4. "IotAdmin/core/sdk"
  5. "IotAdmin/core/sdk/pkg/cronjob"
  6. "fmt"
  7. "time"
  8. "gorm.io/gorm"
  9. )
  10. var (
  11. // jobList 定义的job
  12. jobList map[string]JobExec
  13. )
  14. // InitJob 初始化job
  15. func InitJob() {
  16. initJobList()
  17. Setup(sdk.Runtime.GetDb())
  18. }
  19. // 需要将定义的struct 添加到字典中;
  20. // 字典 key 可以配置到 自动任务 调用目标 中;
  21. func initJobList() {
  22. jobList = map[string]JobExec{
  23. "CleanLog": &CleanLog{},
  24. "ExamplesOne": &ExamplesOne{},
  25. // ...
  26. }
  27. }
  28. // Setup 初始化
  29. func Setup(dbs map[string]*gorm.DB) {
  30. fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore Starting...")
  31. for k, db := range dbs {
  32. sdk.Runtime.SetCrontab(k, cronjob.NewWithSeconds())
  33. setup(k, db)
  34. }
  35. }
  36. func setup(key string, db *gorm.DB) {
  37. crontab := sdk.Runtime.GetCrontabKey(key)
  38. sysJob := models.SysJob{}
  39. jobList := make([]models.SysJob, 0)
  40. err := sysJob.GetList(db, &jobList)
  41. if err != nil {
  42. fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore init error", err)
  43. }
  44. if len(jobList) == 0 {
  45. fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore total:0")
  46. }
  47. _, err = sysJob.RemoveAllEntryID(db)
  48. if err != nil {
  49. fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore remove entry_id error", err)
  50. }
  51. for i := 0; i < len(jobList); i++ {
  52. if jobList[i].JobType == 1 {
  53. j := &HttpJob{}
  54. j.InvokeTarget = jobList[i].InvokeTarget
  55. j.CronExpression = jobList[i].CronExpression
  56. j.JobId = jobList[i].JobId
  57. j.Name = jobList[i].JobName
  58. sysJob.EntryId, err = AddJob(crontab, j)
  59. } else if jobList[i].JobType == 2 {
  60. j := &ExecJob{}
  61. j.InvokeTarget = jobList[i].InvokeTarget
  62. j.CronExpression = jobList[i].CronExpression
  63. j.JobId = jobList[i].JobId
  64. j.Name = jobList[i].JobName
  65. j.Args = jobList[i].Args
  66. sysJob.EntryId, err = AddJob(crontab, j)
  67. }
  68. err = sysJob.Update(db, jobList[i].JobId)
  69. }
  70. // 其中任务
  71. crontab.Start()
  72. fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore start success.")
  73. // 关闭任务
  74. defer crontab.Stop()
  75. select {}
  76. }
  77. // GetJobKeys 获取job key列表
  78. func GetJobKeys() []string {
  79. var list []string
  80. for k := range jobList {
  81. list = append(list, k)
  82. }
  83. return list
  84. }