Calculate the time of the next execution, sleep until then.
func RunAtNight() {
for {
do something.....
// Tomorrow, same time as now.
tomorrow := time.Now().AddDate(0, 0, 1)
// Next run is tomorrow, at 1 AM
next := time.Date(tomorrow.Year(), tomorrow.Month(), tomorrow.Day(), 1, 0, 0, 0, time.Local)
// Sleep until then.
time.Sleep(time.Until(next))
}
}
@YongGopher for these types of things, I find myself only sleeping for half of the intended time. That way I can ideally correct for any delays that may have happened while I was sleeping, as well as emit log lines so that I know the timer is still waiting until the proper time… So in the above code sample, I’d instead do:
func RunAtNight() {
for {
do something.....
// Tomorrow, same time as now.
tomorrow := time.Now().AddDate(0, 0, 1)
// Next run is tomorrow, at 1 AM
next := time.Date(tomorrow.Year(), tomorrow.Month(), tomorrow.Day(), 1, 0, 0, 0, time.Local)
if tu := time.Until(next); tu <= 60 * time.Second {
// log something here
// Sleep until then.
time.Sleep(tu)
else {
// log something here
// Sleep until half of then.
time.Sleep(tu / 2)
}
}
}