How to Trigger a Lambda on a Timer, via AWS Console & Serverless Framework

Two ways to run an AWS Lambda function on a schedule: click it together in the console with an EventBridge trigger, or declare it in serverless.yml. Plus how rate() and cron() expressions actually differ, and how to confirm the thing is really firing.

Originally on DEV.toFebruary 11, 2023
Read the full post on DEV.to

Running a Lambda on a timer is one of those tasks that's genuinely just a few clicks. But the first time you do it, a few things aren't obvious. Do you want CloudWatch Events or EventBridge (they're the same thing now)? Do you use rate() or cron()? And how do you tell it's actually working? This post does the same job two ways: once by hand in the AWS Console, and once as infrastructure-as-code with the Serverless Framework, so you can pick whichever fits how you already deploy.

Either way, the trigger is an EventBridge scheduled rule (the service that used to be branded CloudWatch Events). In the console flow you create a Lambda with a bit of logging, hit "Add trigger", pick EventBridge, create a new rule, and give it a schedule expression like rate(5 minutes). Then you watch CloudWatch Logs to confirm it's invoking. In the Serverless Framework flow, that same rule is a few lines under the function's events key in serverless.yml, and serverless deploy provisions it for you.

Key takeaways

  • rate() vs cron(): rate(5 minutes) for a fixed interval, cron(*/5 * ? * MON-FRI *) for specific times or weekday-only; EventBridge cron has six fields and uses ? for "no specific value"
  • In serverless.yml a function can have multiple schedule events, and enabled: false switches one off without deleting it; schedules are on by default
  • Don't trust the deploy, trust the logs: verify both methods by watching CloudWatch Logs for invocations on your interval

Who this is for

Developers who know their way around Lambda basics and want a recurring, automated invocation: a cleanup job, a polling task, a nightly report. No prior EventBridge experience needed. Handler snippets are shown in both ES module and CommonJS form.

The full walkthrough, with the console screenshots and the complete serverless.yml, is on DEV.to.

Read the full post on DEV.to