@@ -2,6 +2,7 @@ package artifex
22
33import (
44 "errors"
5+ "github.com/robfig/cron/v3"
56 "time"
67)
78
@@ -12,6 +13,7 @@ type Dispatcher struct {
1213 maxQueue int
1314 workers []* Worker
1415 tickers []* DispatchTicker
16+ crons []* DispatchCron
1517 workerPool chan chan Job
1618 jobQueue chan Job
1719 quit chan bool
@@ -34,6 +36,7 @@ func NewDispatcher(maxWorkers int, maxQueue int) *Dispatcher {
3436func (d * Dispatcher ) Start () {
3537 d .workers = []* Worker {}
3638 d .tickers = []* DispatchTicker {}
39+ d .crons = []* DispatchCron {}
3740 d .workerPool = make (chan chan Job , d .maxWorkers )
3841 d .jobQueue = make (chan Job , d .maxQueue )
3942 d .quit = make (chan bool )
@@ -78,8 +81,13 @@ func (d *Dispatcher) Stop() {
7881 d .tickers [i ].Stop ()
7982 }
8083
84+ for i := range d .crons {
85+ d .crons [i ].Stop ()
86+ }
87+
8188 d .workers = []* Worker {}
8289 d .tickers = []* DispatchTicker {}
90+ d .crons = []* DispatchCron {}
8391 d .quit <- true
8492}
8593
@@ -134,6 +142,28 @@ func (d *Dispatcher) DispatchEvery(run func(), interval time.Duration) (*Dispatc
134142 return dt , nil
135143}
136144
145+ // DispatchEvery pushes the given job into the job queue
146+ // each time the cron definition is met
147+ func (d * Dispatcher ) DispatchCron (run func (), cronStr string ) (* DispatchCron , error ) {
148+ if ! d .active {
149+ return nil , errors .New ("dispatcher is not active" )
150+ }
151+
152+ dc := & DispatchCron {cron : cron .New (cron .WithSeconds ())}
153+ d .crons = append (d .crons , dc )
154+
155+ _ , err := dc .cron .AddFunc (cronStr , func () {
156+ d .jobQueue <- Job {Run : run }
157+ })
158+
159+ if err != nil {
160+ return nil , errors .New ("invalid cron definition" )
161+ }
162+
163+ dc .cron .Start ()
164+ return dc , nil
165+ }
166+
137167// DispatchTicker represents a dispatched job ticker
138168// that executes on a given interval. This provides
139169// a means for stopping the execution cycle from continuing.
@@ -147,3 +177,14 @@ func (dt *DispatchTicker) Stop() {
147177 dt .ticker .Stop ()
148178 dt .quit <- true
149179}
180+
181+ // DispatchCron represents a dispatched cron job
182+ // that executes using cron expression formats.
183+ type DispatchCron struct {
184+ cron * cron.Cron
185+ }
186+
187+ // Stops ends the execution cycle for the given cron.
188+ func (c * DispatchCron ) Stop () {
189+ c .cron .Stop ()
190+ }
0 commit comments