DEV Community

Rak
Rak

Posted on • Updated on

Running a scheduled task with Nitric in GO

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:

  1. Go installed on your machine.
  2. 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)
  }
}

Enter fullscreen mode Exit fullscreen mode

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
})
Enter fullscreen mode Exit fullscreen mode

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.

Testing schedules offline with the Nitric Dashboard

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)
})
Enter fullscreen mode Exit fullscreen mode

Note: CRON expressions are also supported!

Top comments (0)