2 min read
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.
You can block until your specified time before continuing execution using this one-liner.
time.Sleep(time.Until(until))
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..... 🎉
}
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
}
}
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..... 🎉
}
In a lot of situations, we would like to be able to schedule functions in Go. While there are many current tools for doing scheduling (such as Cron)...
5 min read
In this post, we'll see how to write workers in Go, how to gracefully shut them down. We'll also look at how to coordinate multiple workers.
8 min read
Comments