Skip to content

Commit f0a137d

Browse files
committed
Use time.Timer instead of time.After
memory is allocated every time time.After is called and is not freed until the timer expires. This could create a memory "leak" of sorts if the user of cron calls snapshots or adds new entries frequently. using time.Timer allows for explicitly stopping and cleaning up the timer on each iteration of the for-loop. So when a snapshot or new entry is added, we can cleanup the timer. see https://groups.google.com/forum/#!topic/golang-nuts/cCdm0Ixwi9A for more details.
1 parent 6f2e828 commit f0a137d

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

cron.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,9 @@ func (c *Cron) run() {
165165
effective = c.entries[0].Next
166166
}
167167

168+
timer := time.NewTimer(effective.Sub(now))
168169
select {
169-
case now = <-time.After(effective.Sub(now)):
170+
case now = <-timer.C:
170171
// Run every entry whose next time was this effective time.
171172
for _, e := range c.entries {
172173
if e.Next != effective {
@@ -186,11 +187,13 @@ func (c *Cron) run() {
186187
c.snapshot <- c.entrySnapshot()
187188

188189
case <-c.stop:
190+
timer.Stop()
189191
return
190192
}
191193

192194
// 'now' should be updated after newEntry and snapshot cases.
193195
now = time.Now().Local()
196+
timer.Stop()
194197
}
195198
}
196199

0 commit comments

Comments
 (0)