Tutorial: build a crontab

In this tutorial, we will validate two cron jobs, render their crontab, and write it to a temporary file.

Install the package

pip install cron-pydantic

Create the configuration

Create example.py:

from pathlib import Path

from cron_pydantic import CronConfiguration

config = CronConfiguration.model_validate(
    {
        "environment": {"PATH": "/usr/local/bin:/usr/bin"},
        "job": {
            "backup": {
                "schedule": "0 2 * * *",
                "command": "/opt/jobs/backup",
            },
            "weekly-report": {
                "schedule": "@weekly",
                "command": "/opt/jobs/report",
                "enabled": False,
            },
        },
        "path": Path("build/crontab"),
    }
)

print(config.to_cron())
print(config.write())

Run it:

python example.py

The output includes the rendered entries and ends with build/crontab:

# Generated by cron-pydantic
PATH=/usr/local/bin:/usr/bin

# cron-pydantic: backup
0 2 * * * /opt/jobs/backup
# cron-pydantic: weekly-report
# @weekly /opt/jobs/report

Notice that the disabled job remains visible as a comment. The file contains the same text printed by to_cron().

Parse the result

Add these lines to example.py:

loaded = CronConfiguration.load("build/crontab")
print(loaded.job["backup"].command)

Run the script again. The final line is:

/opt/jobs/backup

You have now completed a render-write-parse round trip without modifying the host scheduler.