init.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. "ExamplesOne": &ExamplesOne{},
  24. // ...
  25. }
  26. }
  27. // Setup 初始化
  28. func Setup(dbs map[string]*gorm.DB) {
  29. fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore Starting...")
  30. for k, db := range dbs {
  31. sdk.Runtime.SetCrontab(k, cronjob.NewWithSeconds())
  32. setup(k, db)
  33. }
  34. }
  35. func setup(key string, db *gorm.DB) {
  36. crontab := sdk.Runtime.GetCrontabKey(key)
  37. sysJob := models.SysJob{}
  38. jobList := make([]models.SysJob, 0)
  39. err := sysJob.GetList(db, &jobList)
  40. if err != nil {
  41. fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore init error", err)
  42. }
  43. if len(jobList) == 0 {
  44. fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore total:0")
  45. }
  46. _, err = sysJob.RemoveAllEntryID(db)
  47. if err != nil {
  48. fmt.Println(time.Now().Format(timeFormat), " [ERROR] JobCore remove entry_id error", err)
  49. }
  50. for i := 0; i < len(jobList); i++ {
  51. if jobList[i].JobType == 1 {
  52. j := &HttpJob{}
  53. j.InvokeTarget = jobList[i].InvokeTarget
  54. j.CronExpression = jobList[i].CronExpression
  55. j.JobId = jobList[i].JobId
  56. j.Name = jobList[i].JobName
  57. sysJob.EntryId, err = AddJob(crontab, j)
  58. } else if jobList[i].JobType == 2 {
  59. j := &ExecJob{}
  60. j.InvokeTarget = jobList[i].InvokeTarget
  61. j.CronExpression = jobList[i].CronExpression
  62. j.JobId = jobList[i].JobId
  63. j.Name = jobList[i].JobName
  64. j.Args = jobList[i].Args
  65. sysJob.EntryId, err = AddJob(crontab, j)
  66. }
  67. err = sysJob.Update(db, jobList[i].JobId)
  68. }
  69. // 其中任务
  70. crontab.Start()
  71. fmt.Println(time.Now().Format(timeFormat), " [INFO] JobCore start success.")
  72. // 关闭任务
  73. defer crontab.Stop()
  74. select {}
  75. }
  76. // GetJobKeys 获取job key列表
  77. func GetJobKeys() []string {
  78. var list []string
  79. for k := range jobList {
  80. list = append(list, k)
  81. }
  82. return list
  83. }