Skip to Content
๐ŸŽ‰ Bref 3.0 is released. Read more โ†’

Cron tasks on AWS Lambda

A Lambda function can be invoked on a schedule using the schedule event. This is useful for running cron tasks, such as sending emails or cleaning up data. For example:

serverless.yml
functions: cron: # ... events: # the schedule can be defined as a rate - schedule: rate(1 hour) # or as a cron expression - schedule: cron(0 12 * * ? *)

CLI commands

Cron events can be used to run CLI commands with the Console runtime.

In that case, use the php-xx-console runtime (for example php-84-console).

This is usually best when coupled with a framework like Laravel or Symfony, or when porting an existing cron task to AWS Lambda.

serverless.yml
functions: # ... cron: handler: artisan runtime: php-84-console events: - schedule: rate: rate(1 hour) # The command needs to be passed as a JSON string # (that is why it's quoted twice: '"..."') input: '"my-command --option=value"'

The configuration above will run php artisan my-command --option=value every hour in the Lambda function named โ€œcronโ€.

Note that Laravel already provides a schedulerย  that can be used instead of the schedule event. If you want to use it instead, run the artisan schedule:run command every minute:

serverless.yml
functions: # ... artisan: handler: artisan runtime: php-84-console events: - schedule: rate: rate(1 minute) input: '"schedule:run"'

Read more about the options for the schedule event in the Serverless documentationย .

Cron functions

On top of running CLI cron tasks with the php-xx-console runtime, we can also run event-driven functions (using the PHP function runtime) as cron tasks.

serverless.yml
functions: # ... cron: handler: App\MyCronHandler runtime: php-84 events: - schedule: rate: rate(1 hour)

The handler can be a class implementing the Handler interface:

namespace App; use Bref\Context\Context; class MyCronHandler implements \Bref\Event\Handler { public function handle($event, Context $context): void { echo 'Hello ' . $event['name'] ?? 'world'; } }

The configuration above will run MyCronHandler::handle() every hour.

It is possible to provide data inside the $event variable via the input option:

serverless.yml
functions: cron: events: - schedule: rate: rate(1 hour) input: foo: bar hello: world

Read more about the options for the schedule event in the Serverless documentationย .

Last updated on