@@ -19,6 +19,7 @@ type Cron struct {
19
19
snapshot chan []* Entry
20
20
running bool
21
21
ErrorLog * log.Logger
22
+ location * time.Location
22
23
}
23
24
24
25
// Job is an interface for submitted cron jobs.
@@ -74,15 +75,21 @@ func (s byTime) Less(i, j int) bool {
74
75
return s [i ].Next .Before (s [j ].Next )
75
76
}
76
77
77
- // New returns a new Cron job runner.
78
+ // New returns a new Cron job runner, in the Local time zone .
78
79
func New () * Cron {
80
+ return NewWithLocation (time .Now ().Location ())
81
+ }
82
+
83
+ // NewWithLocation returns a new Cron job runner.
84
+ func NewWithLocation (location * time.Location ) * Cron {
79
85
return & Cron {
80
86
entries : nil ,
81
87
add : make (chan * Entry ),
82
88
stop : make (chan struct {}),
83
89
snapshot : make (chan []* Entry ),
84
90
running : false ,
85
91
ErrorLog : nil ,
92
+ location : location ,
86
93
}
87
94
}
88
95
@@ -131,6 +138,11 @@ func (c *Cron) Entries() []*Entry {
131
138
return c .entrySnapshot ()
132
139
}
133
140
141
+ // Location gets the time zone location
142
+ func (c * Cron ) Location () * time.Location {
143
+ return c .location
144
+ }
145
+
134
146
// Start the cron scheduler in its own go-routine, or no-op if already started.
135
147
func (c * Cron ) Start () {
136
148
if c .running {
@@ -156,7 +168,7 @@ func (c *Cron) runWithRecovery(j Job) {
156
168
// access to the 'running' state variable.
157
169
func (c * Cron ) run () {
158
170
// Figure out the next activation times for each entry.
159
- now := time .Now ().Local ( )
171
+ now := time .Now ().In ( c . location )
160
172
for _ , entry := range c .entries {
161
173
entry .Next = entry .Schedule .Next (now )
162
174
}
@@ -177,6 +189,7 @@ func (c *Cron) run() {
177
189
timer := time .NewTimer (effective .Sub (now ))
178
190
select {
179
191
case now = <- timer .C :
192
+ now = now .In (c .location )
180
193
// Run every entry whose next time was this effective time.
181
194
for _ , e := range c .entries {
182
195
if e .Next != effective {
@@ -191,7 +204,7 @@ func (c *Cron) run() {
191
204
192
205
case newEntry := <- c .add :
193
206
c .entries = append (c .entries , newEntry )
194
- newEntry .Next = newEntry .Schedule .Next (time .Now ().Local ( ))
207
+ newEntry .Next = newEntry .Schedule .Next (time .Now ().In ( c . location ))
195
208
196
209
case <- c .snapshot :
197
210
c .snapshot <- c .entrySnapshot ()
@@ -202,7 +215,7 @@ func (c *Cron) run() {
202
215
}
203
216
204
217
// 'now' should be updated after newEntry and snapshot cases.
205
- now = time .Now ().Local ( )
218
+ now = time .Now ().In ( c . location )
206
219
timer .Stop ()
207
220
}
208
221
}
0 commit comments