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

2 1

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay