diff --git a/README.md b/README.md index 504d004..3774b41 100644 --- a/README.md +++ b/README.md @@ -48,12 +48,15 @@ Create a `config.yml` file in the same directory as the binary (or `/etc/scron/` Optionally, you can specify the `weekday` field (0=Sunday, 1=Monday, ..., 6=Saturday) to restrict jobs to specific days of the week. +You can also optionally specify the `timezone` field to set the timezone for each job. Default is UTC. You can use any timezone supported by Go (e.g., `Europe/Berlin`). + ```yaml jobs: - name: "System Health Check" minute: "*/5" hour: "*" weekday: "*" + timezone: "Europe/Berlin" command: "curl -f http://localhost:8080/health || exit 1" - name: "Daily Backup" diff --git a/config.go b/config.go index 5f4edf4..74b674f 100644 --- a/config.go +++ b/config.go @@ -21,6 +21,7 @@ type jobconfig struct { Hour string `yaml:"hour"` Minute string `yaml:"minute"` Weekday string `yaml:"weekday"` + Timezone string `yaml:"timezone"` Command string `yaml:"command"` Notification string `yaml:"notification,omitempty"` } @@ -66,8 +67,19 @@ func ReadFromFile(path string) (config, error) { } func (jc jobconfig) MatchCurrentTime(t time.Time) (bool, error) { + loc, err := time.LoadLocation("UTC") + if err != nil { + panic(err) + } + + if jc.Timezone != "" { + loc, err = time.LoadLocation(jc.Timezone) + if err != nil { + return false, err + } + } fmt.Println("weekday", jc.Weekday) - matchWeekDay, err := matchTime(jc.Weekday, int(t.Weekday())) + matchWeekDay, err := matchTime(jc.Weekday, int(t.In(loc).Weekday())) if err != nil { return false, err } @@ -75,7 +87,7 @@ func (jc jobconfig) MatchCurrentTime(t time.Time) (bool, error) { return false, nil } - matchHour, err := matchTime(jc.Hour, t.Hour()) + matchHour, err := matchTime(jc.Hour, t.In(loc).Hour()) if err != nil { return false, err } @@ -83,7 +95,7 @@ func (jc jobconfig) MatchCurrentTime(t time.Time) (bool, error) { return false, nil } - matchMinute, err := matchTime(jc.Minute, t.Minute()) + matchMinute, err := matchTime(jc.Minute, t.In(loc).Minute()) if err != nil { return false, err } diff --git a/config.yml.example b/config.yml.example index 7e94d3b..085f592 100644 --- a/config.yml.example +++ b/config.yml.example @@ -3,4 +3,5 @@ jobs: minute: "*" hour: "*" weekday: "*" + timezone: "Europe/Berlin" # optional, default UTC command: "echo 'Juhu'" diff --git a/config_test.go b/config_test.go index abc99b1..5ac99fd 100644 --- a/config_test.go +++ b/config_test.go @@ -168,6 +168,12 @@ func TestMatchJobTime(t *testing.T) { expRes: false, expErrMsg: "cant parse time pattern", }, + { + name: "pass-with-timezone", + job: jobconfig{Hour: "17", Minute: "*", Weekday: "*", Timezone: "Africa/Nairobi"}, + expRes: true, + expErrMsg: "", + }, } for _, tt := range tts {