From a2732bbd1baaabb225a2a89563d6e264077fa68b Mon Sep 17 00:00:00 2001 From: yogi sofiharja Date: Mon, 26 Sep 2022 13:29:13 +0700 Subject: [PATCH] Add SetLocation method to crontab This method allow us to run cron on specific time zone. location can be set after initiating crontab. ``` ctab := crontab.New() err := ctab.SetLocation("Asia/Jakarta") if err != nil { return err } ``` --- crontab.go | 12 ++++++++++++ crontab_test.go | 6 ++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crontab.go b/crontab.go index dad9739..819eebd 100644 --- a/crontab.go +++ b/crontab.go @@ -17,6 +17,7 @@ type Crontab struct { ticker *time.Ticker jobs []*job sync.RWMutex + location *time.Location } // job in cron table @@ -62,6 +63,13 @@ func new(t time.Duration) *Crontab { return c } +// SetLocation to run cron on specific timezone. +// +// Returns error if provided location is not valid +func (c *Crontab) SetLocation(loc *time.Location) { + c.location = loc +} + // AddJob to cron table // // Returns error if: @@ -153,6 +161,10 @@ func (c *Crontab) RunAll() { // RunScheduled jobs func (c *Crontab) runScheduled(t time.Time) { + if c.location != nil { + t = t.In(c.location) + } + tick := getTick(t) c.RLock() defer c.RUnlock() diff --git a/crontab_test.go b/crontab_test.go index 16efa43..a26cdf0 100644 --- a/crontab_test.go +++ b/crontab_test.go @@ -1,7 +1,9 @@ package crontab -import "testing" -import "time" +import ( + "testing" + "time" +) // TestSchedule parse the crontab syntax and compare number of target min/hour/days/month with expected ones func TestSchedule(t *testing.T) {