DEV Community

Cover image for How to schedule a task at a specific time in Go
Stephen Afam-Osemene
Stephen Afam-Osemene

Posted on • Edited on • Originally published at stephenafamo.com

How to schedule a task at a specific time in Go

Looking at Google search traffic, I've seen an increase in queries for "How to schedule task at specific time in Go" leading to my other article about scheduling in Go.

So I've decided to create this article to directly answer the question. You can read the other article for a more detailed look at scheduling in Go.

The one-liner

You can block until your specified time before continuing execution using this one-liner.

time.Sleep(time.Until(until))

Enter fullscreen mode Exit fullscreen mode

For example:

func main() {
    // when we want to wait till
    until, _ := time.Parse(time.RFC3339, "2023-06-22T15:04:05+02:00")

    // and now we wait
    time.Sleep(time.Until(until))

    // Do what ever we want..... 🎉
}

Enter fullscreen mode Exit fullscreen mode

Exiting early

In real world use, it is likely that there are cases where you want to stop the schedule prematurely, to do this, we can accept a context.Context and exit if the context is canceled.

This also has the benefit of properly stopping the timer if it is no longer needed

func waitUntil(ctx context.Context, until time.Time) {
    timer := time.NewTimer(time.Until(until))
    defer timer.Stop()

    select {
    case <-timer.C:
        return
    case <-ctx.Done():
        return
    }
}
Enter fullscreen mode Exit fullscreen mode

Example:

func main() {
    // our context, for now we use context.Background()
    ctx := context.Background()

    // when we want to wait till
    until, _ := time.Parse(time.RFC3339, "2023-06-22T15:04:05+02:00")

    // and now we wait
    waitUntil(ctx, until)

    // Do what ever we want..... 🎉
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)