Timer without library

Hi all!
How can I start function every night at 1 am without using third party library?
Something like

func RunAtNight() {
    for {
            do something.....
            time.Sleep(time.Second * 1) //but do it at 1:am every day
     }
}

Thanks!

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))
    }
}
6 Likes

Cool!
Thanks!

@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)
        }
    }
}
1 Like

Above method is also useful if we should be able to cancel the scheduled run somehow.

Thanks! All works!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.