

# 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?](https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html) 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](backend-lambda.md).

## Write the job
<a name="backend-lambda-schedule-job"></a>

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](backend-keys.md).

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

```javascript
// 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
<a name="backend-lambda-schedule-add"></a>

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

```yaml
# 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](https://docs.aws.amazon.com/scheduler/latest/UserGuide/schedule-types.html). For the event’s other properties, see [ScheduleV2](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-schedulev2.html) 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](backend-lambda-deploy.md).

## Test the job
<a name="backend-lambda-schedule-test"></a>

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.

```bash
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
<a name="backend-lambda-schedule-logs"></a>

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

```bash
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](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs.html) in the AWS Lambda Developer Guide.