1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- package example_basics
- // @snippet_begin(WorkerExample)
- import (
- "context"
- "errors"
- "fmt"
- "time"
- "github.com/qor5/admin/presets"
- "github.com/qor5/admin/worker"
- )
- func MountWorker(b *presets.Builder) {
- wb := worker.New(DB)
- wb.Configure(b)
- defer wb.Listen()
- addJobs(wb)
- }
- func addJobs(w *worker.Builder) {
- w.NewJob("noArgJob").
- Handler(func(ctx context.Context, job worker.QorJobInterface) error {
- job.AddLog("hoho1")
- job.AddLog("hoho2")
- job.AddLog("hoho3")
- return nil
- })
- type ArgJobResource struct {
- F1 string
- F2 int
- F3 bool
- }
- argJb := w.NewJob("argJob").
- Resource(&ArgJobResource{}).
- Handler(func(ctx context.Context, job worker.QorJobInterface) error {
- jobInfo, _ := job.GetJobInfo()
- job.AddLog(fmt.Sprintf("Argument %#+v", jobInfo.Argument))
- return nil
- })
- // you can to customize the resource Editing via GetResourceBuilder()
- argJb.GetResourceBuilder().Editing()
- w.NewJob("progressTextJob").
- Handler(func(ctx context.Context, job worker.QorJobInterface) error {
- job.AddLog("hoho1")
- job.AddLog("hoho2")
- job.AddLog("hoho3")
- job.SetProgressText(`<a href="https://www.google.com">Download users</a>`)
- return nil
- })
- // check ctx.Done() to stop the handler
- w.NewJob("longRunningJob").
- Handler(func(ctx context.Context, job worker.QorJobInterface) error {
- for i := 1; i <= 5; i++ {
- select {
- case <-ctx.Done():
- job.AddLog("job aborted")
- return nil
- default:
- job.AddLog(fmt.Sprintf("%v", i))
- job.SetProgress(uint(i * 20))
- time.Sleep(time.Second)
- }
- }
- return nil
- })
- // insert worker.Schedule to resource to make a job schedulable
- type ScheduleJobResource struct {
- F1 string
- worker.Schedule
- }
- w.NewJob("scheduleJob").
- Resource(&ScheduleJobResource{}).
- Handler(func(ctx context.Context, job worker.QorJobInterface) error {
- jobInfo, _ := job.GetJobInfo()
- job.AddLog(fmt.Sprintf("%#+v", jobInfo.Argument))
- return nil
- })
- w.NewJob("errorJob").
- Handler(func(ctx context.Context, job worker.QorJobInterface) error {
- job.AddLog("=====perform error job")
- return errors.New("imError")
- })
- w.NewJob("panicJob").
- Handler(func(ctx context.Context, job worker.QorJobInterface) error {
- job.AddLog("=====perform panic job")
- panic("letsPanic")
- })
- }
- // @snippet_end
|