DEV Community

Paul Chin Jr.
Paul Chin Jr.

Posted on

Serverless background tasks with OpenJS Architect - Part 2

@scheduled example

Another common background task is @scheduled functions. These functions are invoked on a schedule defined in the app.arc file. These functions are good for cleanup tasks or kicking off other kinds of health checks. Let's make a new project and add a @scheduled function.

The first thing we will need is a fresh Architect project. We can create one directly from the terminal.

npm init @architect ./arc-scheduled-app
cd arc-scheduled-app
npm install @architect/functions
Enter fullscreen mode Exit fullscreen mode

Now we can open up the app.arc file and add a scheduled function to the manifest.

# app.arc

# your project namespace
@app 
arc-scheduled-app

# http functions and routes
@http
get /

# scheduled functions listed by name and rate
@scheduled
daily rate(1 day)
Enter fullscreen mode Exit fullscreen mode

Architect looks for the function named daily in the src/scheduled/daily folder. So let's go ahead and write one.

exports.handler = async function scheduled (event) {
  console.log(JSON.stringify(event, null, 2))
  return
}
Enter fullscreen mode Exit fullscreen mode

When this function is deployed, it is registered to an AWS CloudWatch Event. The event will trigger this function to handle the event payload coming into it. It should be treated as something that happens in the background of your main application to handle work on a regular and periodic cycle.

Let's take a look at the generated sam.json to see how the resource will be created.

From the terminal, run arc deploy --dry-run and take a look at sam.json in the project's root directory. Here we can see the CloudFormation that will generate the rule and the trigger.

"DailyScheduledEvent": {
      "Type": "AWS::Events::Rule",
      "Properties": {
        "ScheduleExpression": "rate(1 day)",
        "Targets": [
          {
            "Arn": {
              "Fn::GetAtt": [
                "DailyScheduledLambda",
                "Arn"
              ]
            },
            "Id": "DailyScheduledLambda"
          }
        ]
      }
    },
Enter fullscreen mode Exit fullscreen mode

This shows that the function is a scheduled event with a rate of being invoked once a day. The rate expression starts when the rule is created at the time of deployment. If you need more fine grained control over the timing, then you'll have to write a Cron expression. For more information about schedule rules, follow the AWS documentation

Stay tuned

In the next part we will look at using Queues with OpenJS Architect!

Top comments (0)