DEV Community

Cover image for Create systemd unit timers
Alberto Gonzalez Escalante
Alberto Gonzalez Escalante

Posted on

Create systemd unit timers

Problem

Run a script every day at midnight using systemd.

Solution

1. Systemd service file

## File: /etc/systemd/system/run-script.service [Unit] Description=Run a script every day at midnight [Service] Type=simple EnvironmentFile=/path/to/environment ExecStart=/path/to/script.sh [Install] WantedBy=multi-user.target 
Enter fullscreen mode Exit fullscreen mode

2. Systemd timer file

## File: /etc/systemd/system/run-script.timer [Unit] Description=Run a script every day at midnight [Timer] OnCalendar=*-*-* 00:00:00 Unit=run-script.service [Install] WantedBy=timers.target 
Enter fullscreen mode Exit fullscreen mode

3. Reload and start the timer

sudo systemctl daemon-reload sudo systemctl enable run-script.timer sudo systemctl enable run-script.service 
Enter fullscreen mode Exit fullscreen mode

Explanation

The systemd unit timers are a powerful feature that allows you to schedule tasks to run at specific times or intervals. They are similar to cron jobs but offer more flexibility and control. You can take advantage of systemd's built-in capabilities like logging and monitoring, environment variables, and more.

Top comments (0)