Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions eventbridge-scheduler-cron-migration/python/sam/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.aws-sam/
samconfig.toml
__pycache__/
*.pyc
222 changes: 222 additions & 0 deletions eventbridge-scheduler-cron-migration/python/sam/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
# Migrate cron to Amazon EventBridge Scheduler with AWS Lambda and Amazon DynamoDB

This pattern helps you **replace cron on a VM** with Amazon EventBridge Scheduler. It reads an existing crontab, creates one schedule per entry, keeps an **execution record** of every run in Amazon DynamoDB, alarms when a job does not report completion, and replays a **missed schedule** after a deployment.

A schedule **survives reboots**, because there is no instance to reboot and no `crontab -l` to lose with the host. You can **migrate one job at a time**, and **roll back by disabling the schedule** without touching the rest.

Learn more about this pattern at Serverless Land Patterns: << Add the live URL here >>

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Requirements

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed
* Python installed, to run the import script. The script needs `boto3` to create schedules; `--dry-run` converts and checks a crontab with no dependencies at all.

## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```
git clone https://github.com/aws-samples/serverless-patterns
```
1. Change directory to the pattern directory:
```
cd serverless-patterns/eventbridge-scheduler-cron-migration/python/sam
```
1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yaml file:
```
sam deploy --guided
```
1. During the prompts:
* Enter a stack name
* Enter the desired AWS Region
* Enter a `ScheduleTimezone`, for example `America/New_York`. A crontab inherits the time zone of the host it runs on; a schedule has to state it.
* Allow SAM CLI to create IAM roles with the required permissions.

Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.
1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing. The `ImportCommand` output is a ready-made import command with every ARN filled in.

### Import the crontab

The stack deploys the machinery; the import script creates the schedules. Convert first and look at the result before anything is created:

```bash
python3 tools/import_crontab.py --crontab tools/examples/crontab \
--dispatcher-arn <DispatcherFunctionArn> \
--role-arn <SchedulerInvokeRoleArn> \
--group <ScheduleGroupName> \
--dlq-arn <ScheduleDeadLetterQueueArn> \
--timezone America/New_York \
--dry-run
```

```
Time zone: America/New_York
2 schedule(s) to import:
nightly-report cron(0 2 * * ? *) <- 0 2 * * * /usr/local/bin/nightly-report.sh --full
hourly-sync cron(0 * * * ? *) <- 0 * * * * /usr/local/bin/sync-inventory.sh
```

Drop `--dry-run` to create them. Re-running the import updates the existing schedules in place, so it is safe to run again as you work through a crontab.

To migrate one job at a time, import a single job with `--only`, or create everything in the `DISABLED` state with `--disabled` and enable each schedule once you have compared a run against the old crontab:

```bash
python3 tools/import_crontab.py --crontab /etc/crontab --only nightly-report --disabled ...
aws scheduler update-schedule --name nightly-report --group-name <ScheduleGroupName> --state ENABLED ...
```

## How it works

An import script, a dispatcher, a table and an alarm replace what a crontab and a mail alias used to do between them.

**One schedule per crontab line.** `tools/import_crontab.py` parses a crontab, converts each entry, and calls `CreateSchedule` once per line with an explicit time zone, a retry policy and a dead-letter queue. Every schedule targets the same Lambda dispatcher and names its job in the payload, so the schedule count matches the crontab line count without one function per job. Schedules live in their own schedule group, so you can list and remove the migration as a unit.

**The conversion is not a copy and paste.** A crontab line and a cron expression look alike, which is what makes the differences expensive:

| | crontab | EventBridge Scheduler |
| --- | --- | --- |
| Fields | 5 | 6, the extra one is `year` |
| Day of week | `0`-`6` from Sunday, `7` also Sunday | `1`-`7` from Sunday, so every number shifts |
| Both day fields | `*` in both is normal | not allowed; one must be `?` |
| Day-of-month **and** day-of-week | ORed together | cannot be expressed |
| `@reboot` | runs at boot | no equivalent |

Copying `0 0 * * 1` across unchanged moves a Monday job to Sunday and produces an expression Scheduler rejects. The importer handles the shift, and refuses what Scheduler cannot express faithfully rather than quietly creating a schedule that fires on the wrong days. Run it against `tools/examples/crontab-unsupported` to see each refusal and its reason.

**Every run leaves an execution record.** The dispatcher writes an item to DynamoDB when a run starts and updates it when the run finishes, keyed on `job#<name>` and `run#<scheduled-time>`. The scheduled time comes from the schedule itself, through the `<aws.scheduler.scheduled-time>` context attribute, not from the clock inside the function. That is what makes a retry address the same record instead of creating a second one, and it is what lets the catch-up function tell a missed window from a completed one. A `marker` item per job holds the last completed window and only ever moves forward.

**The alarm watches for silence.** On completion the dispatcher publishes a `JobCompleted` metric for the job, and a CloudWatch alarm with `TreatMissingData: breaching` fires when that metric does not arrive inside the expected window. This is deliberately the opposite of alarming on errors: the failure a crontab hides is the run that never started, which produces no output, no exit code and no mail, so nothing fires. Set `MonitoredJobDeadlineSeconds` to the business deadline for the job, not to its runtime.

**Catch-up closes the deployment gap.** A schedule missed during a deployment is the case cron has no answer for: if the host was replaced at 02:03 and a job was due at 02:00, that run is simply gone and nothing notices. The catch-up function reads each job's marker, lists the windows that should have fired since, and invokes the dispatcher once per window with that window's scheduled time. The dispatcher's conditional write makes each replay idempotent, so running catch-up twice does not run a job twice.

Catch-up is bounded on purpose. It replays at most `MAX_REPLAYS_PER_JOB` windows per job, and a job with no marker at all looks back `lookbackHours` rather than to the beginning of time, so a first run against an empty table cannot replay a year of windows. Raise either in `src/catchup/app.py` if a longer gap is genuinely possible; a job whose marker is months old will otherwise stop at the cap.

The one-time schedule that triggers catch-up is created by the import script rather than declared in `template.yaml`, for a reason worth knowing: `AWS::Scheduler::Schedule` has no `ActionAfterCompletion` property, and a completed one-time schedule keeps counting against the Region's schedule quota until something deletes it. The API accepts `ActionAfterCompletion=DELETE`, so a schedule created that way removes itself after it fires.

**Rollback** is one call. `update-schedule --state DISABLED` stops a job without deleting its history or touching any other job, which is the property that makes migrating one job at a time safe.

A few limits worth stating plainly. Schedules invoke their targets with 60 second precision, so a run due at 02:00 starts somewhere in that minute. Scheduler adjusts cron schedules for daylight saving time in the time zone you give it: when the clock springs forward onto a time that does not exist the run is skipped, and when it falls back the run happens once rather than twice. Neither is something a crontab on a VM handles better, but both are worth knowing before you move a job that cares.

## Testing

The commands below use the stack outputs. Set `STACK` to your stack name first.

```bash
STACK=<your-stack-name>
GROUP=$(aws cloudformation describe-stacks --stack-name $STACK \
--query "Stacks[0].Outputs[?OutputKey=='ScheduleGroupName'].OutputValue" --output text)
TABLE=$(aws cloudformation describe-stacks --stack-name $STACK \
--query "Stacks[0].Outputs[?OutputKey=='RunHistoryTableName'].OutputValue" --output text)
DISPATCHER=$(aws cloudformation describe-stacks --stack-name $STACK \
--query "Stacks[0].Outputs[?OutputKey=='DispatcherFunctionArn'].OutputValue" --output text)
```

**1. Confirm the conversion.** Run the importer against the unsupported examples and check that each line is refused with a reason:

```bash
python3 tools/import_crontab.py --crontab tools/examples/crontab-unsupported \
--dispatcher-arn $DISPATCHER --role-arn x --group $GROUP --dry-run
```

**2. Confirm the schedules exist**, with the time zone and dead-letter queue attached:

```bash
aws scheduler list-schedules --group-name $GROUP \
--query "Schedules[].{Name:Name,State:State}" --output table
aws scheduler get-schedule --group-name $GROUP --name nightly-report \
--query "{Expression:ScheduleExpression,Timezone:ScheduleExpressionTimezone,DLQ:Target.DeadLetterConfig.Arn}"
```

**3. Run a job without waiting for its window.** Invoke the dispatcher with a scheduled time of your choosing. This is also the CLI test case for the function:

```bash
aws lambda invoke --function-name $DISPATCHER --cli-binary-format raw-in-base64-out \
--payload '{"job":"nightly-report","scheduledTime":"2026-01-01T02:00:00Z","executionId":"manual-1","attempt":1,"scheduleArn":"manual"}' \
response.json && cat response.json
```

Expected: `{"job": "nightly-report", "scheduledTime": "2026-01-01T02:00:00Z", "status": "COMPLETED", "durationMs": ...}`

**4. Confirm the execution record**, which should hold one `run#` item and one `marker`:

```bash
aws dynamodb query --table-name $TABLE \
--key-condition-expression "pk = :pk" \
--expression-attribute-values '{":pk":{"S":"job#nightly-report"}}' \
--query "Items[].{sk:sk.S,status:status.S,scheduled:scheduledTime.S}" --output table
```

**5. Confirm a replay does not run the job twice.** Invoke the same payload again:

```bash
aws lambda invoke --function-name $DISPATCHER --cli-binary-format raw-in-base64-out \
--payload '{"job":"nightly-report","scheduledTime":"2026-01-01T02:00:00Z","executionId":"manual-2","attempt":1,"scheduleArn":"manual"}' \
response.json && cat response.json
```

Expected: `"status": "SKIPPED"`. The window already completed, so the conditional write refused it.

**6. Confirm catch-up finds a missed schedule.** Ask the catch-up function what it would replay, without replaying it:

```bash
CATCHUP=$(aws cloudformation describe-stacks --stack-name $STACK \
--query "Stacks[0].Outputs[?OutputKey=='CatchUpFunctionArn'].OutputValue" --output text)
aws lambda invoke --function-name $CATCHUP --cli-binary-format raw-in-base64-out \
--payload '{"dryRun":true,"lookbackHours":48}' response.json && cat response.json
```

Expected: a `wouldReplay` list of the windows between each job's marker and now. Drop `dryRun` to replay them; every window already recorded comes back `SKIPPED`.

**7. Confirm the alarm treats silence as a failure.** A job that has never completed has no metric at all, so the alarm should settle in `ALARM` rather than `INSUFFICIENT_DATA`:

```bash
aws cloudwatch describe-alarms --alarm-names "$STACK-nightly-report-no-completion" \
--query "MetricAlarms[].{State:StateValue,Reason:StateReason}" --output table
```

### Lambda test event

```json
{
"job": "nightly-report",
"scheduledTime": "2026-01-01T02:00:00Z",
"executionId": "manual-1",
"attempt": 1,
"scheduleArn": "manual"
}
```

### Unit tests

The crontab conversion has a known-answer test suite covering the field count, the day-of-week shift, the `?` rule, the macros and every refusal:

```bash
cd tools && python3 -m unittest -v test_cron_to_scheduler
```

## Cleanup

1. Delete the schedules the importer created. They are not part of the stack, so CloudFormation does not remove them, and a schedule group cannot be deleted while it still holds schedules:
```bash
for name in $(aws scheduler list-schedules --group-name $GROUP --query "Schedules[].Name" --output text); do
aws scheduler delete-schedule --name $name --group-name $GROUP
done
```
1. Delete the stack
```bash
aws cloudformation delete-stack --stack-name STACK_NAME
```
1. Confirm the stack has been deleted
```bash
aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus"
```

----

Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
{
"title": "Migrate cron to Amazon EventBridge Scheduler with AWS Lambda and Amazon DynamoDB",
"description": "Replace cron on a VM: import a crontab as one schedule per job, keep an execution record, alarm on a missing completion, and catch up a missed schedule.",
"language": "Python",
"level": "300",
"framework": "AWS SAM",
"tags": ["cron", "scheduler", "migration", "catch-up"],
"introBox": {
"headline": "How it works",
"text": [
"This pattern replaces cron on a VM with Amazon EventBridge Scheduler. An import script reads an existing crontab, converts each line into a Scheduler cron expression, and creates one schedule per entry targeting a single AWS Lambda dispatcher. Nothing has to be rewritten job by job, because the crontab is the input. The dispatcher routes on the job name carried in the schedule payload, so the number of schedules matches the number of crontab lines without deploying one Lambda function per job. Every schedule is created in its own schedule group, so the migration can be listed, disabled or removed as a unit.",
"Converting a crontab is not a copy and paste. A Scheduler cron expression has six fields rather than five, numbers the days of the week from Sunday as 1 rather than 0, and cannot use the asterisk wildcard in both day fields at once, so a line carried across unchanged can move a Monday job to Sunday or be rejected outright. The importer handles all three conversions, and refuses the lines Scheduler cannot express faithfully rather than creating a schedule that fires on the wrong days. Those include @reboot, which has no equivalent because there is no instance to boot, and a crontab that restricts both the day of the month and the day of the week, which cron treats as a logical OR. A dry run prints the converted expressions, and every refusal with its reason, before anything is created.",
"The dispatcher writes an execution record to an Amazon DynamoDB table when a run starts and updates it when the run finishes, keyed on the scheduled window taken from the schedule's own context attributes rather than from the clock inside the function. Keying on the window is what lets a retry update the same record instead of creating a second one, and what lets the catch-up function tell a missed schedule apart from a completed one. A marker item per job holds the last completed window and only ever moves forward.",
"On completion the dispatcher publishes a metric, and a CloudWatch alarm that treats missing data as breaching fires when that metric does not arrive inside the expected window. The alarm watches for absence rather than for errors, because the failure a crontab hides is the run that never started: it produces no output, no exit code and no mail, so nothing fires. A catch-up function reads each job's marker, lists the windows that should have fired while no schedule was running, and replays them idempotently, which closes the gap a deployment leaves behind.",
"A schedule survives reboots because there is no host to reboot and no crontab to lose along with it. Jobs can be migrated one at a time by importing a single entry or by creating every schedule disabled and enabling them individually, and a rollback is one call to disable one schedule."
]
},
"gitHub": {
"template": {
"templateFile": "template.yaml"
}
},
"resources": {
"bullets": [
{
"text": "Schedule types on EventBridge Scheduler, including the six cron fields and the day-of-week numbering",
"link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/schedule-types.html"
},
{
"text": "Adding context attributes, used here to pass the scheduled time into the run record",
"link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-schedule-context-attributes.html"
},
{
"text": "Managing a schedule: time zones, flexible time windows, retries and dead-letter queues",
"link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-schedule.html"
},
{
"text": "Configuring how CloudWatch alarms treat missing data",
"link": "https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#alarms-and-missing-data"
},
{
"text": "Quotas for EventBridge Scheduler, including the schedule count that completed one-time schedules consume",
"link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/scheduler-quotas.html"
}
]
},
"deploy": {
"text": [
"sam deploy --guided"
]
},
"testing": {
"text": [
"See the GitHub repo for detailed testing instructions."
]
},
"cleanup": {
"text": [
"Delete the schedules the importer created, then delete the stack: <code>sam delete</code>."
]
},
"authors": [
{
"name": "Ifeanyi O.",
"bio": "Developer Experience Engineer at AWS",
"linkedin": "ifeanyi-otuonye",
"twitter": "ifeanyi_otuonye",
"github": "rextheking"
}
]
}
Loading