Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for cron-tz #1369

Open
wants to merge 17 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions pkg/gofr/cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,15 @@ type CronFunc func(ctx *Context)
type Crontab struct {
// contains unexported fields
ticker *time.Ticker
location *time.Location
jobs []*job
container *container.Container

mu sync.RWMutex
}

type job struct {
sec map[int]struct{}
min map[int]struct{}
hour map[int]struct{}
day map[int]struct{}
month map[int]struct{}
dayOfWeek map[int]struct{}
sec, min, hour, day, month, dayOfWeek map[int]struct{}

name string
fn CronFunc
Expand All @@ -62,22 +58,32 @@ type tick struct {
}

// NewCron initializes and returns new cron tab.
func NewCron(cntnr *container.Container) *Crontab {
func NewCron(cntnr *container.Container, options ...func(*Crontab)) *Crontab {
c := &Crontab{
ticker: time.NewTicker(time.Second),
location: time.Local,
container: cntnr,
jobs: make([]*job, 0),
}

for _, option := range options {
option(c)
}

go func() {
for t := range c.ticker.C {
t = t.In(c.location)
c.runScheduled(t)
}
}()

return c
}

func WithTimezone(location *time.Location) func(*Crontab) {
return func(c *Crontab) { c.location = location }
}

// this will compile the regex once instead of compiling it each time when it is being called.
var (
matchSpaces = regexp.MustCompile(`\s+`)
Expand Down
22 changes: 22 additions & 0 deletions pkg/gofr/cron_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -606,3 +606,25 @@ func TestCron_parsePart(t *testing.T) {
})
}
}

func TestCron_WithTimezone(t *testing.T) {
tests := []struct {
name string
option func(*Crontab)
expected *time.Location
}{
{
name: "Factory with timezone option",
option: WithTimezone(time.UTC),
expected: time.UTC,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := NewCron(nil, test.option)
got.ticker.Stop()
assert.Equal(t, test.expected, got.location)
})
}
}
Umang01-hash marked this conversation as resolved.
Show resolved Hide resolved
Loading