[#4394] reschedule the first cron tick to start at 00 second

This commit is contained in:
Gani Georgiev
2024-02-21 19:49:52 +02:00
parent f2ed186540
commit 5a715cc60a
2 changed files with 33 additions and 13 deletions
+30 -13
View File
@@ -22,12 +22,13 @@ type job struct {
// Cron is a crontab-like struct for tasks/jobs scheduling.
type Cron struct {
sync.RWMutex
timezone *time.Location
ticker *time.Ticker
startTimer *time.Timer
jobs map[string]*job
interval time.Duration
interval time.Duration
timezone *time.Location
ticker *time.Ticker
jobs map[string]*job
sync.RWMutex
}
// New create a new Cron struct with default tick interval of 1 minute
@@ -132,6 +133,11 @@ func (c *Cron) Stop() {
c.Lock()
defer c.Unlock()
if c.startTimer != nil {
c.startTimer.Stop()
c.startTimer = nil
}
if c.ticker == nil {
return // already stopped
}
@@ -146,15 +152,26 @@ func (c *Cron) Stop() {
func (c *Cron) Start() {
c.Stop()
c.Lock()
c.ticker = time.NewTicker(c.interval)
c.Unlock()
// delay the ticker to start at 00 of 1 c.interval duration
now := time.Now()
next := now.Add(c.interval).Truncate(c.interval)
delay := next.Sub(now)
go func() {
for t := range c.ticker.C {
c.runDue(t)
}
}()
c.startTimer = time.AfterFunc(delay, func() {
c.Lock()
c.ticker = time.NewTicker(c.interval)
c.Unlock()
// run immediately at 00
c.runDue(time.Now())
// run after each tick
go func() {
for t := range c.ticker.C {
c.runDue(t)
}
}()
})
}
// HasStarted checks whether the current Cron ticker has been started.