github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/model/job/globals.go (about) 1 // Package job is for the scheduling and execution of asynchronous jobs via the 2 // workers. The scheduling is done via the triggers. The jobs are put in queues 3 // before being processed by a worker. 4 package job 5 6 import ( 7 "context" 8 9 "github.com/cozy/cozy-stack/pkg/utils" 10 ) 11 12 // JobSystem is a pair of broker, scheduler linked together. 13 type JobSystem interface { 14 Broker 15 Scheduler 16 utils.Shutdowner 17 } 18 19 type jobSystem struct { 20 Broker 21 Scheduler 22 } 23 24 // Shutdown shuts down the job system. Implement the utils.Shutdowner 25 // interface. 26 func (j jobSystem) Shutdown(ctx context.Context) error { 27 if err := j.Broker.ShutdownWorkers(ctx); err != nil { 28 return err 29 } 30 return j.Scheduler.ShutdownScheduler(ctx) 31 } 32 33 var globalJobSystem JobSystem 34 35 // SystemStart initializes and starts the global jobs system with the given 36 // broker, scheduler instances and workers list. 37 func SystemStart(b Broker, s Scheduler, workersList WorkersList) error { 38 if globalJobSystem != nil { 39 panic("Job system already started") 40 } 41 globalJobSystem = jobSystem{b, s} 42 if err := b.StartWorkers(workersList); err != nil { 43 return err 44 } 45 return s.StartScheduler(b) 46 } 47 48 // System returns the global job system. 49 func System() JobSystem { 50 if globalJobSystem == nil { 51 panic("Job system not initialized") 52 } 53 return globalJobSystem 54 }