Setting up a scheduled job is a common requirement for many modern applications.
With the Nitric SDK, this task is simplified, and you can even test your scheduled jobs offline without needing Terraform.
In this tutorial, we'll walk through setting up a scheduled job that aggregates data every three days using the Nitric SDK in Go.
If you haven't used the Nitric SDK before, then start with this tutorial.
Pre-Requisites:
- Go installed on your machine.
- Nitric SDK for Go.
Step 1: Import Necessary Libraries
Start by importing the necessary libraries into your Go script. In this tutorial, we'll use the nitrictech/go-sdk/nitric
and nitrictech/go-sdk/faas
libraries which provide the needed functions to create and manage scheduled jobs.
import (
"fmt"
"github.com/nitrictech/go-sdk/faas"
"github.com/nitrictech/go-sdk/nitric"
)
func main() {
// TODO: implement your scheduled job here.
if err := nitric.Run(); err != nil {
fmt.Println(err)
}
}
Step 2: Define Your Scheduled Job
Next, define a function for your scheduled job. In this example, we're creating a new scheduled job named "aggregate-data" that will run every three days.
Inside the function, we've added a simple print statement "aggregating data" to demonstrate the job's activity.
nitric.NewSchedule("aggregate-data").Every("3 days", func(ctx *faas.EventContext, _ faas.EventHandler) (*faas.EventContext, error) {
fmt.Println("aggregating data")
return ctx, nil
})
Test Your Scheduled Job Offline
One of the advantages of using the Nitric SDK is the ability to test your scheduled jobs offline. This is particularly useful for debugging and ensuring your jobs are working as expected before deploying them to the cloud.
In just a few steps, you've now created a scheduled job that aggregates data every three days, here are a few more examples showing you how to set up other frequencies.
nitric.NewSchedule("process-often").Every("5 minutes", func(ctx *faas.EventContext, next faas.EventHandler) (*faas.EventContext, error) {
return next(ctx)
})
nitric.NewSchedule("process-sometimes").Every("2 hours", func(ctx *faas.EventContext, next faas.EventHandler) (*faas.EventContext, error) {
return next(ctx)
})
nitric.NewSchedule("process-rarely").Every("30 days", func(ctx *faas.EventContext, next faas.EventHandler) (*faas.EventContext, error) {
return next(ctx)
})
Top comments (0)