This Cookie Cutter template creates systemd timer and service files for scheduled task execution.
Systemd timers are systemd's alternative to cron jobs. They offer several advantages:
- Better logging and error handling through systemd's journal
- Accurate tracking of last execution time
- Ability to run jobs that missed their time slot (e.g., if the system was powered off)
- Can trigger on a variety of time-based and system events
- Integration with systemd's dependency system
A systemd timer setup consists of two units:
- A
.servicefile that defines what to execute - A
.timerfile that controls when the service is triggered
Common timer patterns include:
OnBootSec: Run after system boot with a specified delayOnUnitActiveSec: Run at a fixed intervalOnCalendar: Run at specific times (e.g., "Mon,Wed --* 02:00:00")
- Install cookiecutter:
pipx install cookiecutteror
uvx install cookiecutteretc.
- Generate the template:
cookiecutter gh:path-to-your-repoproject_name: Name of your service (will be used for both .service and .timer files)service_description: Description of what your service doesworking_directory: Full path to your project's working directoryexec_command: The command to execute (full path recommended)boot_delay: Delay after boot before first execution (e.g., "10s", "1min")interval: Time between executions (e.g., "30min", "1h", "1d")
After generating the files:
- Copy the files to systemd's system directory:
sudo cp *.service *.timer /etc/systemd/system/- Reload systemd daemon:
sudo systemctl daemon-reload- Enable and start the timer:
sudo systemctl enable your-service.timer
sudo systemctl start your-service.timerCheck timer status:
systemctl status your-service.timerCheck service status:
systemctl status your-service.serviceList all timers:
systemctl list-timersHere are some examples of more advanced timer configurations:
# Run at midnight every day
OnCalendar=*-*-* 00:00:00
# Run every Monday at 2am
OnCalendar=Mon *-*-* 02:00:00
# Run on the first day of every month
OnCalendar=*-*-01 00:00:00
# Run every 2 hours
OnUnitActiveSec=2h
# Run 1 hour after boot, then every 24 hours
OnBootSec=1h
OnUnitActiveSec=24hYou can modify the generated .timer file to use any of these patterns based on your needs.