Do you want to run a task/function regularly, but don't want to pay an EC2 instance just to run cron? Or don't want to set it up and manage the instance?
You can use AWS lambdas (and zappa) for that. As an example, let's create and deploy a function that prints Hello World!
in the logs once a minute.
First install zappa: pip install zappa
.
Second, build the function that will be called and save it on a file called event_test.py
:
def process_event(event, context):
print('Hello World!')
Then create the zappa_settings.json file:
{
"event_hello": {
"project_name": "event-hello",
"runtime": "python3.6",
"events": [{
"function": "event_test.process_event", // The function to execute
"expression": "rate(1 minute)" // When to execute it (in cron or rate format)
}],
"apigateway_enabled": false, // We don't need a web access to the lambda
"s3_bucket": "<CHANGE_THIS>" // bucket for deploy
}
}
Then deploy it and enable the events with:
$ zappa deploy event_hello
Calling deploy for stage event_hello..
Creating event-hello-event-hello-ZappaLambdaExecutionRole IAM Role..
Creating zappa-permissions policy on event-hello-event-hello-ZappaLambdaExecutionRole IAM Role.
Downloading and installing dependencies..
- sqlite==python36: Using precompiled lambda package
Packaging project as zip.
Uploading event-hello-event-hello-1540029016.zip (5.0MiB)..
100%|█████████████████████████████████████████████████████████████████████████████████| 5.24M/5.24M [00:02<00:00, 1.60MB/s]
Scheduling..
Scheduled event-hello-event-hello-event_test.process_event with expression rate(1 minute)!
Scheduled 25a24ee2d25a447b827d55fd774ecf9a586a4-handler.keep_warm_callback with expression rate(4 minutes)!
Deployment complete!
And now you can see that every minute you get a new 'Hello World!' in the logs - you can check with $ zappa tail
.
Note: the keep_warm reference is to a default zappa event. You can check what it does in the README.
If you want to stop the events but keep the lambda deployed, do:
$ zappa unschedule event_hello
Calling unschedule for stage event_hello..
Unscheduling..
Unscheduled 25a24ee2d25a447b827d55fd774ecf9a586a4-handler.keep_warm_callback.
Unscheduled event-hello-event-hello-event_test.process_event.
And to reenable them, do:
$ zappa schedule event_hello
Calling schedule for stage event_hello..
Scheduling..
Scheduled event-hello-event-hello-event_test.process_event with expression rate(1 minute)!
Scheduled 25a24ee2d25a447b827d55fd774ecf9a586a4-handler.keep_warm_callback with expression rate(4 minutes)!
Have fun!