July 1, 2025

How to Schedule Tasks with Cron and systemd Timers

mr rockstar

How to Schedule Tasks with Cron and systemd Timers
Cheap Dedicated Server

Automating routine tasks is a core strength of Linux systems. Two popular ways to schedule recurring jobs are cron and systemd timers. While cron has been a staple for decades, systemd timers offer more flexibility and are better integrated into modern Linux systems. In this post, we’ll look at how to use both to automate tasks.


Using Cron for Task Scheduling

1. What is Cron?

cron is a time-based job scheduler in Unix-like operating systems. It allows users to run scripts or commands at scheduled times or intervals.

2. Create a Cron Job

To edit your crontab:

crontab -e

A cron job follows this format:

* * * * * /path/to/command

Fields:
Create a Cron Job

┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of the month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)
│ │ │ │ │
* * * * * command to execute

Example:
Run a backup script every day at 2 AM:

0 2 * * * /home/user/scripts/backup.sh

Using systemd Timers

1. Why systemd Timers?

Unlike cron, systemd timers integrate with the systemd init system. They allow for logging, dependency management, and more powerful scheduling options.

2. Create a systemd Service and Timer

Step 1: Create a Service File
Create a Service File

Create /etc/systemd/system/backup.service:

[Unit]
Description=Run Backup Script

[Service]
Type=oneshot
ExecStart=/home/user/scripts/backup.sh

Step 2: Create a Timer File
Create a Timer File

Create /etc/systemd/system/backup.timer:

[Unit]
Description=Daily Backup Timer

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

Step 3: Enable and Start the Timer
Enable and Start the Timer

sudo systemctl daemon-reexec
sudo systemctl enable --now backup.timer

Check the status:

systemctl list-timers

When to Use What?

Featurecronsystemd timer
LoggingMinimalFull systemd logs
Randomized delayNoYes (RandomizedDelaySec)
DependenciesNoYes
User-level supportYesYes (with ~/.config/systemd/user/)

Use cron for simplicity and widespread availability, but prefer systemd timers for better control and system integration.


 

How to Schedule Tasks with Cron and systemd Timers (F.A.Q)

Can cron jobs run as root?

Yes. Use sudo crontab -e to create root-level jobs.

 

Can I use systemd timers without root?

Yes. Create timer and service units in ~/.config/systemd/user/ and enable the user service.

 

How can I see logs of a systemd-timer task?

Use journalctl -u myservice.service to view logs.

What happens if my system was off during a scheduled task?

With systemd, set Persistent=true to ensure the missed task runs on next boot.

Popular Blog Posts