## How to Set Up a systemd Timer This guide provides a quick walkthrough for creating, enabling, and managing systemd timer units to schedule tasks. ### 1. Create a Service Unit First, create a `.service` file that defines the job you want to run. This file will be placed in `/etc/systemd/system/`. **Example: `/etc/systemd/system/mytask.service`** ```ini [Unit] Description=A description for your task [Service] Type=oneshot ExecStart=/usr/local/bin/mytask.sh ``` - `Type=oneshot`: Indicates that this service is a short-lived task. - `ExecStart`: The command or script to be executed. ### 2. Create a Timer Unit Next, create a corresponding `.timer` file. This file defines the schedule for when the service should run. **Example: `/etc/systemd/system/mytask.timer`** ```ini [Unit] Description=Run mytask.service every day at 3 AM [Timer] OnCalendar=*-*-* 03:00:00 Persistent=true [Install] WantedBy=timers.target ``` - `OnCalendar`: Defines a calendar-based schedule. The format is `DayOfWeek Year-Month-Day Hour:Minute:Second`. An asterisk (`*`) matches any value. - `Persistent=true`: If the system was down when the timer should have run, the job will execute as soon as the system boots up. ### 3. Enable and Start the Timer After creating the files, reload the systemd daemon and start the timer: ```bash # Reload systemd to recognize the new files sudo systemctl daemon-reload # Enable the timer to start on boot sudo systemctl enable mytask.timer # Start the timer immediately sudo systemctl start mytask.timer ``` You can do this in one command with `--now`: ```bash sudo systemctl enable --now mytask.timer ``` ### 4. List Existing Timers To see all active timers and when they are scheduled to run next, use the `list-timers` command: ```bash systemctl list-timers ``` **Output Example:** ``` NEXT LEFT LAST PASSED UNIT ACTIVATES Wed 2025-08-27 03:00:00 CEST 12h left Tue 2025-08-26 03:00:00 CEST 9h ago mytask.timer mytask.service ``` - `NEXT`: The next time the timer will trigger. - `LEFT`: Time remaining until the next trigger. - `LAST`: The last time the timer was triggered. To include inactive timers, add the `--all` flag: ```bash systemctl list-timers --all ``` ### 5. Check Status and Logs To check the status of a specific timer or service: ```bash systemctl status mytask.timer systemctl status mytask.service ``` To view the logs generated by your service: ```bash journalctl -u mytask.service ``` To follow the logs in real-time, add the `-f` flag.