View a markdown version of this page

Run a function on a schedule - AWS Amplify

Run a function on a schedule

To run a job at a set rate, such as a nightly report or a cleanup of old rows, invoke an AWS Lambda function from Amazon EventBridge Scheduler. A scheduled run has no signed-in user, so the function calls the Amplify backend with full access. For more information, see What is Amazon EventBridge Scheduler? in the Amazon EventBridge Scheduler User Guide.

Before you start, connect the function to a backend branch. For more information, see Connect an AWS Lambda function.

Write the job

Create the client with awsCredentialsProvider and no publishable key. The SDK signs each request with the credentials of the function’s execution role, and the job runs as service_role, with access to every row. For the roles, see API keys and roles.

The following job counts the rows in the notes table and writes the count to the function’s log:

// functions/notes-report/index.mjs import { createClient } from '@aws-amplifygen3/backend-client-js' import { fromNodeProviderChain } from '@aws-sdk/credential-providers' const admin = createClient(process.env.AMPLIFY_BACKEND_URL, { awsCredentialsProvider: fromNodeProviderChain(), }) export const handler = async () => { const { count, error } = await admin.from('notes').select('*', { count: 'exact', head: true }) if (error) throw new Error(`${error.code}: ${error.message}`) console.log(JSON.stringify({ totalNotes: count })) return { totalNotes: count } }

Add the schedule

In the function’s AWS Serverless Application Model (AWS SAM) template, add a ScheduleV2 event to the function’s Events:

# functions/template.yaml, under the function's Properties Events: Daily: Type: ScheduleV2 Properties: ScheduleExpression: rate(1 day)

AWS SAM creates the schedule and the IAM role that EventBridge Scheduler uses to invoke the function. For the rate and cron expressions, see Schedule types on EventBridge Scheduler. For the event’s other properties, see ScheduleV2 in the AWS SAM Developer Guide.

Deploy the template with sam deploy, once for each environment. Each environment’s schedule runs the job against that environment’s backend branch. For more information, see Deploy functions with your app.

Test the job

To run the job once without waiting for the schedule, run the following command. Replace my-app-functions-preview-NotesReport-EXAMPLE with the FunctionName output of your stack.

aws lambda invoke --function-name my-app-functions-preview-NotesReport-EXAMPLE \ --cli-binary-format raw-in-base64-out --payload '{}' out.json cat out.json

You should see the job’s result, such as {"totalNotes":3}.

Read the job’s logs

Run the following command to show the function’s log events from the last hour:

aws logs tail /aws/lambda/my-app-functions-preview-NotesReport-EXAMPLE --since 1h --format short

Each run writes a line such as {"totalNotes":3}. A failed run writes the error code and message that the job threw. To show new runs as they happen, add --follow. For more information, see Using CloudWatch Logs with Lambda in the AWS Lambda Developer Guide.