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:
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-81-console
).
This is usually best when coupled with a framework like Laravel or Symfony, or when porting an existing cron task to AWS Lambda.
functions:
# ...
cron:
handler: artisan
runtime: php-81-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 (opens in a new tab) that can be used instead of the schedule
event. If you want to use it instead, run the artisan schedule:run
command every minute:
functions:
# ...
artisan:
handler: artisan
runtime: php-81-console
events:
- schedule:
rate: rate(1 minute)
input: '"schedule:run"'
Read more about the options for the schedule
event in the Serverless documentation (opens in a new tab).
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.
functions:
# ...
cron:
handler: App\MyCronHandler
runtime: php-81
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:
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 (opens in a new tab).