Cade Rosche

Build and Deploy an Automated Task Scheduler with Go

Author: Cade Rosche

Published: 12/30/2023

Example repo: github.com/cprosche/go-task-scheduler-example

TL;DR

What task scheduling library should I choose?

You could always build your own. But using a well-tested library will save you a lot of time and heartache.

I compared a list of Go task/job scheduling libraries. I used the list from awesome-go.com/job-scheduler.

After opening every GitHub repo in the list, I found gocron. It had the most stars in the list and I liked what I saw in the example of its API.

Here's a simple example of gocron's API:

            
package main

import (
    "fmt"
    "time"

    "github.com/go-co-op/gocron"
)

func task() {
    fmt.Println("I am a task")
}

func main() {
    // Create a new scheduler
    s := gocron.NewScheduler(time.UTC)

    // Schedule a task to run every second
    s.Every(1).Second().Do(task)

    // Schedule a task to run at 
    // 10:30 every day
    s.Every(1).Day().At("10:30").Do(task)

    // Start the scheduler
    s.StartBlocking()
}
            
        

The above code will run the task function every second and at 10:30 AM every day, which prints "I am a task" to the console.

What can I make my task scheduler do for me?

You could integrate this with with any service that provides an API or webhooks.

Some examples include:

There are also some Go libraries you might find useful for building tasks:

You can find more useful libraries in the awesome-go repo.

And don't forget that you can use any of the Go standard library: https://pkg.go.dev/std.

How do I deploy my task scheduler so that it runs all the time?

There are a million different ways you could deploy your task scheduler.

This article will focus on deploying to Railway.

Conclusion

I hope this article helped you get started with building and deploying a task scheduler with Go.

If you have any questions or comments, please reach out to me on via email at caderosche@gmail.com.