sys_job.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package service
  2. import (
  3. "time"
  4. "github.com/go-admin-team/go-admin-core/sdk/service"
  5. "github.com/robfig/cron/v3"
  6. "git.cestong.com.cn/cecf/config-center-server/app/jobs"
  7. "git.cestong.com.cn/cecf/config-center-server/app/jobs/models"
  8. "git.cestong.com.cn/cecf/config-center-server/common/dto"
  9. )
  10. type SysJob struct {
  11. service.Service
  12. Cron *cron.Cron
  13. }
  14. // RemoveJob 删除job
  15. func (e *SysJob) RemoveJob(c *dto.GeneralDelDto) error {
  16. var err error
  17. var data models.SysJob
  18. err = e.Orm.Table(data.TableName()).First(&data, c.Id).Error
  19. if err != nil {
  20. e.Log.Errorf("db error: %s", err)
  21. return err
  22. }
  23. cn := jobs.Remove(e.Cron, data.EntryId)
  24. select {
  25. case res := <-cn:
  26. if res {
  27. err = e.Orm.Table(data.TableName()).Where("entry_id = ?", data.EntryId).Update("entry_id", 0).Error
  28. if err != nil {
  29. e.Log.Errorf("db error: %s", err)
  30. }
  31. return err
  32. }
  33. case <-time.After(time.Second * 1):
  34. e.Msg = "操作超时!"
  35. return nil
  36. }
  37. return nil
  38. }
  39. // StartJob 启动任务
  40. func (e *SysJob) StartJob(c *dto.GeneralGetDto) error {
  41. var data models.SysJob
  42. var err error
  43. err = e.Orm.Table(data.TableName()).First(&data, c.Id).Error
  44. if err != nil {
  45. e.Log.Errorf("db error: %s", err)
  46. return err
  47. }
  48. if data.JobType == 1 {
  49. var j = &jobs.HttpJob{}
  50. j.InvokeTarget = data.InvokeTarget
  51. j.CronExpression = data.CronExpression
  52. j.JobId = data.JobId
  53. j.Name = data.JobName
  54. data.EntryId, err = jobs.AddJob(e.Cron, j)
  55. if err != nil {
  56. e.Log.Errorf("jobs AddJob[HttpJob] error: %s", err)
  57. }
  58. } else {
  59. var j = &jobs.ExecJob{}
  60. j.InvokeTarget = data.InvokeTarget
  61. j.CronExpression = data.CronExpression
  62. j.JobId = data.JobId
  63. j.Name = data.JobName
  64. j.Args = data.Args
  65. data.EntryId, err = jobs.AddJob(e.Cron, j)
  66. if err != nil {
  67. e.Log.Errorf("jobs AddJob[ExecJob] error: %s", err)
  68. }
  69. }
  70. if err != nil {
  71. return err
  72. }
  73. err = e.Orm.Table(data.TableName()).Where(c.Id).Updates(&data).Error
  74. if err != nil {
  75. e.Log.Errorf("db error: %s", err)
  76. }
  77. return err
  78. }