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
- Building with Go is great because it is a simple language to learn and deploy, while also beiong preformant.
- Use gocron, it is the task scheduler with the most stars on github and has been great to use so far.
- Deploying with railway.app is super easy and cheap.
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:
- ntfy: Use ntfy to send custom push notification to any phone.
- Twilio: Use Twilio to send text messages.
- SendGrid: Use SendGrid to send emails.
- open-meteo.com: Use open-meteo to get weather data.
There are also some Go libraries you might find useful for building tasks:
- colly: Build web scrapers. Visit any website and extract data from it.
- Fiber: API Framework. Access your tasks via an API.
- Slack API in Go: Send messages to Slack.
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.
- You could deploy it to a VPS like DigitalOcean, Linode, or AWS.
- You could deploy on a self-hosted server, like a Raspberry Pi.
- You can use a managed service, like Heroku, or Railway.
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.