AWS CDK(v2): Execute Lambda by Cron

Using CDK, you can easily schedule Lambda to run using EventBridge. We will use the so-called cron method to describe the schedule.

One thing to be a little careful about is that a rule can be triggered multiple times in response to a single event. (From Official Troubleshooting). If you can manage that, it is very easy and useful.

Version

  • node: 16.13.1
  • aws-cdk: 2.2.0
  • tsc: 4.5.4

HowTo

For example, if you want to call myLambda every 10 minutes, you can write it as follows. You can specify the content of the event to be passed to Lambda in the {path:"/call"} part.

/// lib/xyz-stack.ts
export class XyzStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
...

    const myLambda = new NodejsFunction(this, "MyAwesomeFunction", {
      entry: path.join(__dirname, './lambda/main.ts'),
      handler: "handler",
    });

    const rule = new Rule(this, "CallMyLambda", {
      schedule: Schedule.cron({
        year: "*",
        month: "*",
        day: "*",
        hour: "*",
        minute: "*/10",
      }),
      targets: [new LambdaFunction(myLambda, {
        event: RuleTargetInput.fromObject({path: "/call"}), // specify an object to pass the lambda handler.
      })],
    });

...
}

Reference