Scheduling Functions
Amplify offers the ability to schedule Functions to run on specific intervals using natural language or cron expressions. To get started, specify the schedule
property in defineFunction
:
import { defineFunction } from "@aws-amplify/backend";
export const weeklyDigest = defineFunction({ name: "weekly-digest", schedule: "every week",});
Function schedules are powered by Amazon EventBridge rules, and can be leveraged to address use cases such as:
- generating a "front page" of top-performing posts
- generating a weekly digest of top-performing posts
- generating a monthly report of warehouse inventory
Their handlers can be typed using the EventBridgeHandler
type:
import type { EventBridgeHandler } from "aws-lambda";
export const handler: EventBridgeHandler<"Scheduled Event", null, void> = async (event) => { console.log("event", JSON.stringify(event, null, 2))}
Schedules can either be a single interval, or multiple intervals:
import { defineFunction } from "@aws-amplify/backend";
export const generateReport = defineFunction({ name: "generate-report", schedule: ["every week", "every month", "every year"],});
Schedules can also be defined to execute using minutes or hours with a shorthand syntax:
import { defineFunction } from "@aws-amplify/backend";
export const drinkSomeWater = defineFunction({ name: "drink-some-water", schedule: "every 1h"})
Or combined to create complex schedules:
import { defineFunction } from "@aws-amplify/backend";
export const remindMe = defineFunction({ name: "remind-me", schedule: [ // every sunday at midnight "every week", // every tuesday at 5pm "0 17 * ? 3 *", // every wednesday at 5pm "0 17 * ? 4 *", // every thursday at 5pm "0 17 * ? 5 *", // every friday at 5pm "0 17 * ? 6 *", ]})
Using natural language
Schedules can be written using natural language, using terms you use every day. Amplify supports the following time periods:
day
will always start at midnightweek
will always start on Sunday at midnightmonth
will always start on the first of the month at midnightyear
will always start on the first of the year at midnightm
for minutesh
for hours
Natural language expressions are prefixed with "every":
import { defineFunction } from "@aws-amplify/backend";
export const drinkSomeWater = defineFunction({ name: "drink-some-water", schedule: "every 1h"})
Using cron expressions
Schedules can be written using cron expressions.
import { defineFunction } from "@aws-amplify/backend";
export const remindMe = defineFunction({ name: "remind-me-to-take-the-trash-out", schedule: [ // every tuesday at 9am "0 9 * ? 3 *", // every friday at 9am "0 9 * ? 6 *", ]})