-
-
Notifications
You must be signed in to change notification settings - Fork 309
/
scheduler.go
1572 lines (1361 loc) · 43.4 KB
/
scheduler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gocron
import (
"context"
"fmt"
"reflect"
"sort"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/robfig/cron/v3"
"go.uber.org/atomic"
)
type limitMode int8
// Scheduler struct stores a list of Jobs and the location of time used by the Scheduler
type Scheduler struct {
jobsMutex sync.RWMutex
jobs map[uuid.UUID]*Job
locationMutex sync.RWMutex
location *time.Location
running *atomic.Bool // represents if the scheduler is running at the moment or not
time TimeWrapper // wrapper around time.Time
timer func(d time.Duration, f func()) *time.Timer
executor *executor // executes jobs passed via chan
tags sync.Map // for storing tags when unique tags is set
tagsUnique bool // defines whether tags should be unique
updateJob bool // so the scheduler knows to create a new job or update the current
waitForInterval bool // defaults jobs to waiting for first interval to start
singletonMode bool // defaults all jobs to use SingletonMode()
startBlockingStopChanMutex sync.Mutex
startBlockingStopChan chan struct{} // stops the scheduler
// tracks whether we're in a chain of scheduling methods for a job
// a chain is started with any of the scheduler methods that operate
// upon a job and are ended with one of [ Do(), Update() ] - note that
// Update() calls Do(), so really they all end with Do().
// This allows the caller to begin with any job related scheduler method
// and only with one of [ Every(), EveryRandom(), Cron(), CronWithSeconds(), MonthFirstWeekday() ]
inScheduleChain *uuid.UUID
}
// days in a week
const allWeekDays = 7
// NewScheduler creates a new Scheduler
func NewScheduler(loc *time.Location) *Scheduler {
executor := newExecutor()
s := &Scheduler{
location: loc,
running: atomic.NewBool(false),
time: &trueTime{},
executor: &executor,
tagsUnique: false,
timer: afterFunc,
}
s.jobsMutex.Lock()
s.jobs = map[uuid.UUID]*Job{}
s.jobsMutex.Unlock()
return s
}
// SetMaxConcurrentJobs limits how many jobs can be running at the same time.
// This is useful when running resource intensive jobs and a precise start time is not critical.
//
// Note: WaitMode and RescheduleMode provide details on usage and potential risks.
func (s *Scheduler) SetMaxConcurrentJobs(n int, mode limitMode) {
s.executor.limitModeMaxRunningJobs = n
s.executor.limitMode = mode
}
// StartBlocking starts all jobs and blocks the current thread.
// This blocking method can be stopped with Stop() from a separate goroutine.
func (s *Scheduler) StartBlocking() {
s.StartAsync()
s.startBlockingStopChanMutex.Lock()
s.startBlockingStopChan = make(chan struct{}, 1)
s.startBlockingStopChanMutex.Unlock()
<-s.startBlockingStopChan
s.startBlockingStopChanMutex.Lock()
s.startBlockingStopChan = nil
s.startBlockingStopChanMutex.Unlock()
}
// StartAsync starts all jobs without blocking the current thread
func (s *Scheduler) StartAsync() {
if !s.IsRunning() {
s.start()
}
}
// start starts the scheduler, scheduling and running jobs
func (s *Scheduler) start() {
s.executor.start()
s.setRunning(true)
s.runJobs()
}
func (s *Scheduler) runJobs() {
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
for _, job := range s.jobs {
ctx, cancel := context.WithCancel(context.Background())
job.mu.Lock()
job.ctx = ctx
job.cancel = cancel
job.mu.Unlock()
s.runContinuous(job)
}
}
func (s *Scheduler) setRunning(b bool) {
s.running.Store(b)
}
// IsRunning returns true if the scheduler is running
func (s *Scheduler) IsRunning() bool {
return s.running.Load()
}
// Jobs returns the list of Jobs from the scheduler
func (s *Scheduler) Jobs() []*Job {
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
jobs := make([]*Job, len(s.jobs))
var counter int
for _, job := range s.jobs {
jobs[counter] = job
counter++
}
return jobs
}
// JobsMap returns a map of job uuid to job
func (s *Scheduler) JobsMap() map[uuid.UUID]*Job {
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
jobs := make(map[uuid.UUID]*Job, len(s.jobs))
for id, job := range s.jobs {
jobs[id] = job
}
return jobs
}
// Name sets the name of the current job.
//
// If the scheduler is running using WithDistributedLocker(), the job name is used
// as the distributed lock key. If the job name is not set, the function name is used as the distributed lock key.
func (s *Scheduler) Name(name string) *Scheduler {
job := s.getCurrentJob()
job.jobName = name
return s
}
// Len returns the number of Jobs in the Scheduler
func (s *Scheduler) Len() int {
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
return len(s.jobs)
}
// ChangeLocation changes the default time location
func (s *Scheduler) ChangeLocation(newLocation *time.Location) {
s.locationMutex.Lock()
defer s.locationMutex.Unlock()
s.location = newLocation
}
// Location provides the current location set on the scheduler
func (s *Scheduler) Location() *time.Location {
s.locationMutex.RLock()
defer s.locationMutex.RUnlock()
return s.location
}
type nextRun struct {
duration time.Duration
dateTime time.Time
}
// scheduleNextRun Compute the instant when this Job should run next
func (s *Scheduler) scheduleNextRun(job *Job) (bool, nextRun) {
now := s.now()
if !s.jobPresent(job) {
return false, nextRun{}
}
lastRun := now
if job.neverRan() {
// Increment startAtTime to the future
if !job.startAtTime.IsZero() && job.startAtTime.Before(now) {
dur := s.durationToNextRun(job.startAtTime, job).duration
job.setStartAtTime(job.startAtTime.Add(dur))
if job.startAtTime.Before(now) {
diff := now.Sub(job.startAtTime)
dur := s.durationToNextRun(job.startAtTime, job).duration
var count time.Duration
if dur != 0 {
count = diff / dur
if diff%dur != 0 {
count++
}
}
job.setStartAtTime(job.startAtTime.Add(dur * count))
}
}
} else {
lastRun = job.NextRun()
}
if !job.shouldRun() {
_ = s.RemoveByID(job)
return false, nextRun{}
}
next := s.durationToNextRun(lastRun, job)
jobNextRun := job.NextRun()
if jobNextRun.After(now) {
job.setLastRun(now)
} else {
job.setLastRun(jobNextRun)
}
if next.dateTime.IsZero() {
next.dateTime = lastRun.Add(next.duration)
job.setNextRun(next.dateTime)
} else {
job.setNextRun(next.dateTime)
}
return true, next
}
// durationToNextRun calculate how much time to the next run, depending on unit
func (s *Scheduler) durationToNextRun(lastRun time.Time, job *Job) nextRun {
// job can be scheduled with .StartAt()
if job.getFirstAtTime() == 0 && job.getStartAtTime().After(lastRun) {
sa := job.getStartAtTime()
if job.unit == days || job.unit == weeks || job.unit == months {
job.addAtTime(
time.Duration(sa.Hour())*time.Hour +
time.Duration(sa.Minute())*time.Minute +
time.Duration(sa.Second())*time.Second,
)
}
return nextRun{duration: sa.Sub(s.now()), dateTime: sa}
}
var next nextRun
switch job.getUnit() {
case milliseconds, seconds, minutes, hours:
next.duration = s.calculateDuration(job)
case days:
next = s.calculateDays(job, lastRun)
case weeks:
if len(job.scheduledWeekdays) != 0 { // weekday selected, Every().Monday(), for example
next = s.calculateWeekday(job, lastRun)
} else {
next = s.calculateWeeks(job, lastRun)
}
if next.dateTime.Before(job.getStartAtTime()) {
return s.durationToNextRun(job.getStartAtTime(), job)
}
case months:
next = s.calculateMonths(job, lastRun)
case duration:
next.duration = job.getDuration()
case crontab:
next.dateTime = job.cronSchedule.Next(lastRun)
next.duration = next.dateTime.Sub(lastRun)
}
return next
}
func (s *Scheduler) calculateMonths(job *Job, lastRun time.Time) nextRun {
// Special case: negative days from the end of the month
if len(job.daysOfTheMonth) == 1 && job.daysOfTheMonth[0] < 0 {
return calculateNextRunForLastDayOfMonth(s, job, lastRun, job.daysOfTheMonth[0])
}
if len(job.daysOfTheMonth) != 0 { // calculate days to job.daysOfTheMonth
nextRunDateMap := make(map[int]nextRun)
for _, day := range job.daysOfTheMonth {
nextRunDateMap[day] = calculateNextRunForMonth(s, job, lastRun, day)
}
nextRunResult := nextRun{}
for _, val := range nextRunDateMap {
if nextRunResult.dateTime.IsZero() {
nextRunResult = val
} else if nextRunResult.dateTime.Sub(val.dateTime).Milliseconds() > 0 {
nextRunResult = val
}
}
return nextRunResult
}
next := s.roundToMidnightAndAddDSTAware(lastRun, job.getFirstAtTime()).AddDate(0, job.getInterval(), 0)
return nextRun{duration: until(lastRun, next), dateTime: next}
}
func calculateNextRunForLastDayOfMonth(s *Scheduler, job *Job, lastRun time.Time, dayBeforeLastOfMonth int) nextRun {
// Calculate the last day of the next month, by adding job.interval+1 months (i.e. the
// first day of the month after the next month), and subtracting one day, unless the
// last run occurred before the end of the month.
addMonth := job.getInterval()
atTime := job.getAtTime(lastRun)
if testDate := lastRun.AddDate(0, 0, -dayBeforeLastOfMonth); testDate.Month() != lastRun.Month() &&
!s.roundToMidnightAndAddDSTAware(lastRun, atTime).After(lastRun) {
// Our last run was on the last day of this month.
addMonth++
atTime = job.getFirstAtTime()
}
next := time.Date(lastRun.Year(), lastRun.Month(), 1, 0, 0, 0, 0, s.Location()).
Add(atTime).
AddDate(0, addMonth, 0).
AddDate(0, 0, dayBeforeLastOfMonth)
return nextRun{duration: until(lastRun, next), dateTime: next}
}
func calculateNextRunForMonth(s *Scheduler, job *Job, lastRun time.Time, dayOfMonth int) nextRun {
atTime := job.getAtTime(lastRun)
natTime := atTime
hours, minutes, seconds := s.deconstructDuration(atTime)
jobDay := time.Date(lastRun.Year(), lastRun.Month(), dayOfMonth, hours, minutes, seconds, 0, s.Location())
difference := absDuration(lastRun.Sub(jobDay))
next := lastRun
if jobDay.Before(lastRun) { // shouldn't run this month; schedule for next interval minus day difference
next = next.AddDate(0, job.getInterval(), -0)
next = next.Add(-difference)
natTime = job.getFirstAtTime()
} else {
if job.getInterval() == 1 && !jobDay.Equal(lastRun) { // every month counts current month
next = next.AddDate(0, job.getInterval()-1, 0)
} else { // should run next month interval
next = next.AddDate(0, job.getInterval(), 0)
natTime = job.getFirstAtTime()
}
next = next.Add(difference)
}
if atTime != natTime {
next = next.Add(-atTime).Add(natTime)
}
return nextRun{duration: until(lastRun, next), dateTime: next}
}
func (s *Scheduler) calculateWeekday(job *Job, lastRun time.Time) nextRun {
daysToWeekday := s.remainingDaysToWeekday(lastRun, job)
totalDaysDifference := s.calculateTotalDaysDifference(lastRun, daysToWeekday, job)
acTime := job.getAtTime(lastRun)
if totalDaysDifference > 0 {
acTime = job.getFirstAtTime()
}
next := s.roundToMidnightAndAddDSTAware(lastRun, acTime).AddDate(0, 0, totalDaysDifference)
return nextRun{duration: until(lastRun, next), dateTime: next}
}
func (s *Scheduler) calculateWeeks(job *Job, lastRun time.Time) nextRun {
totalDaysDifference := int(job.getInterval()) * 7
var next time.Time
atTimes := job.atTimes
for _, at := range atTimes {
n := s.roundToMidnightAndAddDSTAware(lastRun, at)
if n.After(s.now()) {
next = n
break
}
}
if next.IsZero() {
next = s.roundToMidnightAndAddDSTAware(lastRun, job.getFirstAtTime()).AddDate(0, 0, totalDaysDifference)
}
return nextRun{duration: until(lastRun, next), dateTime: next}
}
func (s *Scheduler) calculateTotalDaysDifference(lastRun time.Time, daysToWeekday int, job *Job) int {
if job.getInterval() > 1 {
weekDays := job.Weekdays()
if job.lastRun.Weekday() != weekDays[len(weekDays)-1] {
return daysToWeekday
}
if daysToWeekday > 0 {
return int(job.getInterval())*7 - (allWeekDays - daysToWeekday)
}
return int(job.getInterval()) * 7
}
if daysToWeekday == 0 { // today, at future time or already passed
lastRunAtTime := time.Date(lastRun.Year(), lastRun.Month(), lastRun.Day(), 0, 0, 0, 0, s.Location()).Add(job.getAtTime(lastRun))
if lastRun.Before(lastRunAtTime) {
return 0
}
return 7
}
return daysToWeekday
}
func (s *Scheduler) calculateDays(job *Job, lastRun time.Time) nextRun {
nextRunAtTime := s.roundToMidnightAndAddDSTAware(lastRun, job.getAtTime(lastRun)).In(s.Location())
if s.now().After(nextRunAtTime) || s.now() == nextRunAtTime {
nextRunAtTime = nextRunAtTime.AddDate(0, 0, job.getInterval())
}
return nextRun{duration: until(lastRun, nextRunAtTime), dateTime: nextRunAtTime}
}
func until(from time.Time, until time.Time) time.Duration {
return until.Sub(from)
}
func in(scheduleWeekdays []time.Weekday, weekday time.Weekday) bool {
in := false
for _, weekdayInSchedule := range scheduleWeekdays {
if int(weekdayInSchedule) == int(weekday) {
in = true
break
}
}
return in
}
func (s *Scheduler) calculateDuration(job *Job) time.Duration {
interval := job.getInterval()
switch job.getUnit() {
case milliseconds:
return time.Duration(interval) * time.Millisecond
case seconds:
return time.Duration(interval) * time.Second
case minutes:
return time.Duration(interval) * time.Minute
default:
return time.Duration(interval) * time.Hour
}
}
func (s *Scheduler) remainingDaysToWeekday(lastRun time.Time, job *Job) int {
weekDays := job.Weekdays()
sort.Slice(weekDays, func(i, j int) bool {
return weekDays[i] < weekDays[j]
})
equals := false
lastRunWeekday := lastRun.Weekday()
index := sort.Search(len(weekDays), func(i int) bool {
b := weekDays[i] >= lastRunWeekday
if b {
equals = weekDays[i] == lastRunWeekday
}
return b
})
// check atTime
if equals {
if s.roundToMidnightAndAddDSTAware(lastRun, job.getAtTime(lastRun)).After(lastRun) {
return 0
}
index++
}
if index < len(weekDays) {
return int(weekDays[index] - lastRunWeekday)
}
return int(weekDays[0]) + allWeekDays - int(lastRunWeekday)
}
// absDuration returns the abs time difference
func absDuration(a time.Duration) time.Duration {
if a >= 0 {
return a
}
return -a
}
func (s *Scheduler) deconstructDuration(d time.Duration) (hours int, minutes int, seconds int) {
hours = int(d.Seconds()) / int(time.Hour/time.Second)
minutes = (int(d.Seconds()) % int(time.Hour/time.Second)) / int(time.Minute/time.Second)
seconds = int(d.Seconds()) % int(time.Minute/time.Second)
return
}
// roundToMidnightAndAddDSTAware truncates time to midnight and "adds" duration in a DST aware manner
func (s *Scheduler) roundToMidnightAndAddDSTAware(t time.Time, d time.Duration) time.Time {
hours, minutes, seconds := s.deconstructDuration(d)
return time.Date(t.Year(), t.Month(), t.Day(), hours, minutes, seconds, 0, s.Location())
}
// NextRun datetime when the next Job should run.
func (s *Scheduler) NextRun() (*Job, time.Time) {
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
if len(s.jobs) <= 0 {
return nil, time.Time{}
}
var jobID uuid.UUID
var nearestRun time.Time
for _, job := range s.jobs {
nr := job.NextRun()
if (nr.Before(nearestRun) || nearestRun.IsZero()) && s.now().Before(nr) {
nearestRun = nr
jobID = job.id
}
}
return s.jobs[jobID], nearestRun
}
// EveryRandom schedules a new period Job that runs at random intervals
// between the provided lower (inclusive) and upper (inclusive) bounds.
// The default unit is Seconds(). Call a different unit in the chain
// if you would like to change that. For example, Minutes(), Hours(), etc.
func (s *Scheduler) EveryRandom(lower, upper int) *Scheduler {
job := s.getCurrentJob()
job.setRandomInterval(lower, upper)
return s
}
// Every schedules a new periodic Job with an interval.
// Interval can be an int, time.Duration or a string that
// parses with time.ParseDuration().
// Negative intervals will return an error.
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
//
// The job is run immediately, unless:
// * StartAt or At is set on the job,
// * WaitForSchedule is set on the job,
// * or WaitForScheduleAll is set on the scheduler.
func (s *Scheduler) Every(interval interface{}) *Scheduler {
job := s.getCurrentJob()
switch interval := interval.(type) {
case int:
job.interval = interval
if interval <= 0 {
job.error = wrapOrError(job.error, ErrInvalidInterval)
}
case time.Duration:
if interval <= 0 {
job.error = wrapOrError(job.error, ErrInvalidInterval)
}
job.setInterval(0)
job.setDuration(interval)
job.setUnit(duration)
case string:
d, err := time.ParseDuration(interval)
if err != nil {
job.error = wrapOrError(job.error, err)
}
if d <= 0 {
job.error = wrapOrError(job.error, ErrInvalidInterval)
}
job.setDuration(d)
job.setUnit(duration)
default:
job.error = wrapOrError(job.error, ErrInvalidIntervalType)
}
return s
}
func (s *Scheduler) run(job *Job) {
if !s.IsRunning() {
return
}
job.mu.Lock()
if job.function == nil {
job.mu.Unlock()
s.Remove(job)
return
}
defer job.mu.Unlock()
if job.runWithDetails {
switch len(job.parameters) {
case job.parametersLen:
job.parameters = append(job.parameters, job.copy())
case job.parametersLen + 1:
job.parameters[job.parametersLen] = job.copy()
default:
// something is really wrong and we should never get here
job.error = wrapOrError(job.error, ErrInvalidFunctionParameters)
return
}
}
s.executor.jobFunctions <- job.jobFunction.copy()
}
func (s *Scheduler) runContinuous(job *Job) {
shouldRun, next := s.scheduleNextRun(job)
if !shouldRun {
return
}
if !job.getStartsImmediately() {
job.setStartsImmediately(true)
} else {
s.run(job)
}
nr := next.dateTime.Sub(s.now())
if nr < 0 {
job.setLastRun(s.now())
shouldRun, next := s.scheduleNextRun(job)
if !shouldRun {
return
}
nr = next.dateTime.Sub(s.now())
}
job.setTimer(s.timer(nr, func() {
if !next.dateTime.IsZero() {
for {
n := s.now().UnixNano() - next.dateTime.UnixNano()
if n >= 0 {
break
}
select {
case <-s.executor.ctx.Done():
case <-time.After(time.Duration(n)):
}
}
}
s.runContinuous(job)
}))
}
// RunAll run all Jobs regardless if they are scheduled to run or not
func (s *Scheduler) RunAll() {
s.RunAllWithDelay(0)
}
// RunAllWithDelay runs all Jobs with the provided delay in between each Job
func (s *Scheduler) RunAllWithDelay(d time.Duration) {
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
for _, job := range s.jobs {
s.run(job)
s.time.Sleep(d)
}
}
// RunByTag runs all the Jobs containing a specific tag
// regardless of whether they are scheduled to run or not
func (s *Scheduler) RunByTag(tag string) error {
return s.RunByTagWithDelay(tag, 0)
}
// RunByTagWithDelay is same as RunByTag but introduces a delay between
// each Job execution
func (s *Scheduler) RunByTagWithDelay(tag string, d time.Duration) error {
jobs, err := s.FindJobsByTag(tag)
if err != nil {
return err
}
for _, job := range jobs {
s.run(job)
s.time.Sleep(d)
}
return nil
}
// Remove specific Job by function
//
// Removing a job stops that job's timer. However, if a job has already
// been started by the job's timer before being removed, the only way to stop
// it through gocron is to use DoWithJobDetails and access the job's Context which
// informs you when the job has been canceled.
//
// Alternatively, the job function would need to have implemented a means of
// stopping, e.g. using a context.WithCancel() passed as params to Do method.
//
// The above are based on what the underlying library suggests https://pkg.go.dev/time#Timer.Stop.
func (s *Scheduler) Remove(job interface{}) {
fName := getFunctionName(job)
j := s.findJobByTaskName(fName)
s.removeJobsUniqueTags(j)
s.removeByCondition(func(someJob *Job) bool {
return someJob.funcName == fName
})
}
// RemoveByReference removes specific Job by reference
func (s *Scheduler) RemoveByReference(job *Job) {
_ = s.RemoveByID(job)
}
func (s *Scheduler) findJobByTaskName(name string) *Job {
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
for _, job := range s.jobs {
if job.funcName == name {
return job
}
}
return nil
}
func (s *Scheduler) removeJobsUniqueTags(job *Job) {
if job == nil {
return
}
if s.tagsUnique && len(job.tags) > 0 {
for _, tag := range job.tags {
s.tags.Delete(tag)
}
}
}
func (s *Scheduler) removeByCondition(shouldRemove func(*Job) bool) {
s.jobsMutex.Lock()
defer s.jobsMutex.Unlock()
for _, job := range s.jobs {
if shouldRemove(job) {
s.stopJob(job)
delete(s.jobs, job.id)
}
}
}
func (s *Scheduler) stopJob(job *Job) {
job.mu.Lock()
if job.runConfig.mode == singletonMode {
s.executor.singletonWgs.Delete(job.singletonWg)
}
job.mu.Unlock()
job.stop()
}
// RemoveByTag will remove jobs that match the given tag.
func (s *Scheduler) RemoveByTag(tag string) error {
return s.RemoveByTags(tag)
}
// RemoveByTags will remove jobs that match all given tags.
func (s *Scheduler) RemoveByTags(tags ...string) error {
jobs, err := s.FindJobsByTag(tags...)
if err != nil {
return err
}
for _, job := range jobs {
_ = s.RemoveByID(job)
}
return nil
}
// RemoveByTagsAny will remove jobs that match any one of the given tags.
func (s *Scheduler) RemoveByTagsAny(tags ...string) error {
var errs error
mJob := make(map[*Job]struct{})
for _, tag := range tags {
jobs, err := s.FindJobsByTag(tag)
if err != nil {
errs = wrapOrError(errs, fmt.Errorf("%s: %s", err.Error(), tag))
}
for _, job := range jobs {
mJob[job] = struct{}{}
}
}
for job := range mJob {
_ = s.RemoveByID(job)
}
return errs
}
// RemoveByID removes the job from the scheduler looking up by id
func (s *Scheduler) RemoveByID(job *Job) error {
s.jobsMutex.Lock()
defer s.jobsMutex.Unlock()
if _, ok := s.jobs[job.id]; ok {
s.removeJobsUniqueTags(job)
s.stopJob(job)
delete(s.jobs, job.id)
return nil
}
return ErrJobNotFound
}
// FindJobsByTag will return a slice of jobs that match all given tags
func (s *Scheduler) FindJobsByTag(tags ...string) ([]*Job, error) {
var jobs []*Job
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
Jobs:
for _, job := range s.jobs {
if job.hasTags(tags...) {
jobs = append(jobs, job)
continue Jobs
}
}
if len(jobs) > 0 {
return jobs, nil
}
return nil, ErrJobNotFoundWithTag
}
// MonthFirstWeekday sets the job to run the first specified weekday of the month
func (s *Scheduler) MonthFirstWeekday(weekday time.Weekday) *Scheduler {
_, month, day := s.time.Now(time.UTC).Date()
if day < 7 {
return s.Cron(fmt.Sprintf("0 0 %d %d %d", day, month, weekday))
}
return s.Cron(fmt.Sprintf("0 0 %d %d %d", day, (month+1)%12, weekday))
}
// LimitRunsTo limits the number of executions of this job to n.
// Upon reaching the limit, the job is removed from the scheduler.
func (s *Scheduler) LimitRunsTo(i int) *Scheduler {
job := s.getCurrentJob()
job.LimitRunsTo(i)
return s
}
// SingletonMode prevents a new job from starting if the prior job has not yet
// completed its run
//
// Warning: do not use this mode if your jobs will continue to stack
// up beyond the ability of the limit workers to keep up. An example of
// what NOT to do:
//
// s.Every("1s").SingletonMode().Do(func() {
// // this will result in an ever-growing number of goroutines
// // blocked trying to send to the buffered channel
// time.Sleep(10 * time.Minute)
// })
func (s *Scheduler) SingletonMode() *Scheduler {
job := s.getCurrentJob()
job.SingletonMode()
return s
}
// SingletonModeAll prevents new jobs from starting if the prior instance of the
// particular job has not yet completed its run
//
// Warning: do not use this mode if your jobs will continue to stack
// up beyond the ability of the limit workers to keep up. An example of
// what NOT to do:
//
// s := gocron.NewScheduler(time.UTC)
// s.SingletonModeAll()
//
// s.Every("1s").Do(func() {
// // this will result in an ever-growing number of goroutines
// // blocked trying to send to the buffered channel
// time.Sleep(10 * time.Minute)
// })
func (s *Scheduler) SingletonModeAll() {
s.singletonMode = true
}
// TaskPresent checks if specific job's function was added to the scheduler.
func (s *Scheduler) TaskPresent(j interface{}) bool {
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
for _, job := range s.jobs {
if job.funcName == getFunctionName(j) {
return true
}
}
return false
}
func (s *Scheduler) jobPresent(j *Job) bool {
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
if _, ok := s.jobs[j.id]; ok {
return true
}
return false
}
// Clear clears all Jobs from this scheduler
func (s *Scheduler) Clear() {
s.stopJobs()
s.jobsMutex.Lock()
defer s.jobsMutex.Unlock()
s.jobs = make(map[uuid.UUID]*Job)
// If unique tags was enabled, delete all the tags loaded in the tags sync.Map
if s.tagsUnique {
s.tags.Range(func(key interface{}, value interface{}) bool {
s.tags.Delete(key)
return true
})
}
}
// Stop stops the scheduler. This is a no-op if the scheduler is already stopped.
// It waits for all running jobs to finish before returning, so it is safe to assume that running jobs will finish when calling this.
func (s *Scheduler) Stop() {
if s.IsRunning() {
s.stop()
}
}
func (s *Scheduler) stop() {
s.stopJobs()
s.executor.stop()
s.StopBlockingChan()
s.setRunning(false)
}
func (s *Scheduler) stopJobs() {
s.jobsMutex.RLock()
defer s.jobsMutex.RUnlock()
for _, job := range s.jobs {
job.stop()
}
}
func (s *Scheduler) doCommon(jobFun interface{}, params ...interface{}) (*Job, error) {
job := s.getCurrentJob()
s.inScheduleChain = nil
jobUnit := job.getUnit()
jobLastRun := job.LastRun()
if job.getAtTime(jobLastRun) != 0 && (jobUnit <= hours || jobUnit >= duration) {
job.error = wrapOrError(job.error, ErrAtTimeNotSupported)
}
if len(job.scheduledWeekdays) != 0 && jobUnit != weeks {
job.error = wrapOrError(job.error, ErrWeekdayNotSupported)
}
if job.unit != crontab && job.getInterval() == 0 {
if job.unit != duration {
job.error = wrapOrError(job.error, ErrInvalidInterval)
}
}
if job.error != nil {
// delete the job from the scheduler as this job
// cannot be executed
_ = s.RemoveByID(job)
return nil, job.error
}
val := reflect.ValueOf(jobFun)
for val.Kind() == reflect.Ptr {
val = val.Elem()
}
if val.Kind() != reflect.Func {
// delete the job for the same reason as above
_ = s.RemoveByID(job)
return nil, ErrNotAFunction
}
var fname string
if val == reflect.ValueOf(jobFun) {
fname = getFunctionName(jobFun)
} else {
fname = getFunctionNameOfPointer(jobFun)
}
if job.funcName != fname {
job.function = jobFun
if val != reflect.ValueOf(jobFun) {
job.function = val.Interface()
}
job.parameters = params
job.funcName = fname
}
expectedParamLength := val.Type().NumIn()
if job.runWithDetails {
expectedParamLength--
}
if len(params) != expectedParamLength {
_ = s.RemoveByID(job)
job.error = wrapOrError(job.error, ErrWrongParams)