worker.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package example_basics
  2. // @snippet_begin(WorkerExample)
  3. import (
  4. "context"
  5. "errors"
  6. "fmt"
  7. "time"
  8. "github.com/qor5/admin/presets"
  9. "github.com/qor5/admin/worker"
  10. )
  11. func MountWorker(b *presets.Builder) {
  12. wb := worker.New(DB)
  13. wb.Configure(b)
  14. defer wb.Listen()
  15. addJobs(wb)
  16. }
  17. func addJobs(w *worker.Builder) {
  18. w.NewJob("noArgJob").
  19. Handler(func(ctx context.Context, job worker.QorJobInterface) error {
  20. job.AddLog("hoho1")
  21. job.AddLog("hoho2")
  22. job.AddLog("hoho3")
  23. return nil
  24. })
  25. type ArgJobResource struct {
  26. F1 string
  27. F2 int
  28. F3 bool
  29. }
  30. argJb := w.NewJob("argJob").
  31. Resource(&ArgJobResource{}).
  32. Handler(func(ctx context.Context, job worker.QorJobInterface) error {
  33. jobInfo, _ := job.GetJobInfo()
  34. job.AddLog(fmt.Sprintf("Argument %#+v", jobInfo.Argument))
  35. return nil
  36. })
  37. // you can to customize the resource Editing via GetResourceBuilder()
  38. argJb.GetResourceBuilder().Editing()
  39. w.NewJob("progressTextJob").
  40. Handler(func(ctx context.Context, job worker.QorJobInterface) error {
  41. job.AddLog("hoho1")
  42. job.AddLog("hoho2")
  43. job.AddLog("hoho3")
  44. job.SetProgressText(`<a href="https://www.google.com">Download users</a>`)
  45. return nil
  46. })
  47. // check ctx.Done() to stop the handler
  48. w.NewJob("longRunningJob").
  49. Handler(func(ctx context.Context, job worker.QorJobInterface) error {
  50. for i := 1; i <= 5; i++ {
  51. select {
  52. case <-ctx.Done():
  53. job.AddLog("job aborted")
  54. return nil
  55. default:
  56. job.AddLog(fmt.Sprintf("%v", i))
  57. job.SetProgress(uint(i * 20))
  58. time.Sleep(time.Second)
  59. }
  60. }
  61. return nil
  62. })
  63. // insert worker.Schedule to resource to make a job schedulable
  64. type ScheduleJobResource struct {
  65. F1 string
  66. worker.Schedule
  67. }
  68. w.NewJob("scheduleJob").
  69. Resource(&ScheduleJobResource{}).
  70. Handler(func(ctx context.Context, job worker.QorJobInterface) error {
  71. jobInfo, _ := job.GetJobInfo()
  72. job.AddLog(fmt.Sprintf("%#+v", jobInfo.Argument))
  73. return nil
  74. })
  75. w.NewJob("errorJob").
  76. Handler(func(ctx context.Context, job worker.QorJobInterface) error {
  77. job.AddLog("=====perform error job")
  78. return errors.New("imError")
  79. })
  80. w.NewJob("panicJob").
  81. Handler(func(ctx context.Context, job worker.QorJobInterface) error {
  82. job.AddLog("=====perform panic job")
  83. panic("letsPanic")
  84. })
  85. }
  86. // @snippet_end