# Automate system administration tasks by scheduling jobs

> Run commands on a schedule with cron, once later with at, and the modern way with systemd timers.

Source: https://aminbytes.dev/bytes/administrative-tasks/scheduling-jobs/


Backups at night, log cleanup every week, a reminder in ten minutes: an admin's best work happens while nobody is
watching. Linux has three ways to run things without you: **cron** for jobs that repeat, **at** for a job that runs
once later, and **systemd timers**, the modern option that most distributions now use for their own housekeeping.

## cron: jobs that repeat

`cron` is a small daemon that wakes up every minute, reads its tables, and runs what's due. The package and
service names differ:

| | Debian / Ubuntu | RHEL / Fedora |
| --- | --- | --- |
| Package | `cron` | `cronie` |
| Service | `cron` | `crond` |
| Log | `journalctl -u cron` | `/var/log/cron` |

### The crontab format

Each job is one line: five time fields and a command.

```text
# ┌──────── minute        0-59
# │ ┌────── hour          0-23
# │ │ ┌──── day of month  1-31
# │ │ │ ┌── month         1-12 (or jan-dec)
# │ │ │ │ ┌ day of week   0-7  (0 and 7 are Sunday, or sun-sat)
# │ │ │ │ │
  30 2 * * * /usr/local/bin/backup.sh
```

Each field takes more than plain numbers:

| Syntax | Meaning | Example | Runs |
| --- | --- | --- | --- |
| `*` | Every value | `* * * * *` | Every minute |
| `a,b` | A list | `0 8,12,18 * * *` | At 08:00, 12:00 and 18:00 |
| `a-b` | A range | `0 9 * * 1-5` | 09:00 Monday to Friday |
| `*/n` | Every n-th | `*/15 * * * *` | Every 15 minutes |
| `a-b/n` | Steps in a range | `0 8-18/2 * * *` | Every two hours from 08:00 to 18:00 |

There are also shortcuts that replace all five fields: `@reboot` (once at startup), `@hourly`, `@daily` (or
`@midnight`), `@weekly`, `@monthly` and `@yearly` (or `@annually`).

 (Side note: If you restrict both day of month and day of week, cron runs the job when **either** matches. `0 0 13 * 5` runs on every 13th *and* every Friday, not only on Friday the 13th.)

Two traps catch almost everyone:

- **cron has a tiny environment.** `PATH` is short (often `/usr/bin:/bin`), the shell is `/bin/sh`, and your
  `.bashrc` is not read. Use full paths, or set `PATH=` at the top of the crontab.
- **`%` is special.** In the command part, `%` means "newline". Escape it: `date +\%F`.

Any output a job prints is mailed to its owner (if a mail system is installed). Set `MAILTO=you@example.com` at the
top of the table to send it elsewhere, or `MAILTO=""` to turn it off. Many admins redirect output to a log instead:
`>> /var/log/backup.log 2>&1`.

### User crontabs: the crontab command

Every user can have their own table. You never edit the file directly: the `crontab` command does it, checks the
syntax and tells cron.

```bash
crontab -e              # edit your crontab in $EDITOR (or $VISUAL)
crontab -l              # list it
crontab -r              # remove it, without asking!
crontab -i -r           # remove it, but ask first
crontab mycron.txt      # replace your crontab with the contents of a file
sudo crontab -u bob -l  # root can work on another user's table
```

A first job you can try. It writes the time to a file every minute:

```console
$ crontab -l
no crontab for alice
$ (crontab -l 2>/dev/null; echo '* * * * * date >> /tmp/cron-test.txt') | crontab -
$ crontab -l
* * * * * date >> /tmp/cron-test.txt
$ sleep 120; cat /tmp/cron-test.txt
Tue Dec  1 14:31:01 CET 2026
Tue Dec  1 14:32:01 CET 2026
```

Remove it again with `crontab -r` when you're done.

The tables live under `/var/spool/cron/`:

- Debian / Ubuntu: `/var/spool/cron/crontabs/alice`
- RHEL / Fedora: `/var/spool/cron/alice`

Only root can read that directory. Look, but use `crontab -e` to change anything.

### The system crontab: /etc/crontab and /etc/cron.d/

System jobs go in `/etc/crontab` or in their own file in `/etc/cron.d/`. Packages drop files there (for example
`/etc/cron.d/certbot`). These have **one extra field**: the user to run as, right before the command.

```text {title="/etc/crontab (Debian 12)"}
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || { cd / && run-parts --report /etc/cron.daily; }
47 6    * * 7   root    test -x /usr/sbin/anacron || { cd / && run-parts --report /etc/cron.weekly; }
52 6    1 * *   root    test -x /usr/sbin/anacron || { cd / && run-parts --report /etc/cron.monthly; }
```

A user crontab line has 5 time fields and a command. A line in `/etc/crontab` or `/etc/cron.d/*` has 5 time
fields, a **user** and a command. Mixing them up is a favourite exam question.

### The drop-in folders: /etc/cron.hourly, daily, weekly, monthly

The simplest way to schedule a system job: put an executable script in one of these folders. No time fields at all.

```text
/etc/cron.hourly/
/etc/cron.daily/      ← logrotate, man-db, apt or dnf cleanup live here
/etc/cron.weekly/
/etc/cron.monthly/
```

`run-parts` runs every executable file in the folder, in name order. Debian runs them from `/etc/crontab` (above).
RHEL runs `cron.hourly` from `/etc/cron.d/0hourly` and leaves daily, weekly and monthly to **anacron**, which
catches up on jobs missed while the machine was off.

```bash
sudo install -m 755 cleanup.sh /etc/cron.daily/cleanup
```

> [!WARNING]
> On Debian and Ubuntu, `run-parts` skips files with a dot in the name. `/etc/cron.daily/cleanup.sh` silently never
> runs; call it `cleanup`. The same naming rule applies to files in `/etc/cron.d/`. And the script must be
> executable.

### Who may use cron: cron.allow and cron.deny

| Situation | Who can use `crontab` |
| --- | --- |
| `/etc/cron.allow` exists | Only users listed in it (`cron.deny` is ignored) |
| Only `/etc/cron.deny` exists | Everyone **except** users listed in it |
| Neither exists | Depends on the build: all users on Debian, only root on some others |

Both files hold one user name per line. RHEL ships an empty `/etc/cron.deny`, so everyone may use cron. On most
systems root can use it whatever the files say. These files only control the `crontab` command: jobs in `/etc/crontab` and `/etc/cron.d/` are not
affected.

## at: a job that runs once

`at` reads commands from you and runs them once at a set time. It needs the `atd` daemon, which isn't always
installed:

```bash
sudo apt install at        # Debian / Ubuntu
sudo dnf install at        # RHEL / Fedora
sudo systemctl enable --now atd
```

Type the commands, then press <kbd>Ctrl</kbd>+<kbd>D</kbd>:

```console
$ at now + 5 minutes
warning: commands will be executed using /bin/sh
at> echo "tea is ready" > /tmp/tea.txt
at> <EOT>
job 3 at Tue Dec  1 14:35:00 2026
```

`at` understands many time formats:

```bash
at 17:00                 # today at 17:00 (or tomorrow if that's passed)
at 9am tomorrow
at noon                  # also: midnight, teatime (16:00)
at now + 2 hours         # minutes, hours, days, weeks
at 08:00 Dec 24          # a date: month name and day, or MM/DD/YY, DD.MM.YY
at -f backup.sh 23:00    # read the commands from a file instead
```

`at` remembers your current directory and environment, so jobs run like you typed them right there.

Manage the queue with three commands:

```console
$ atq
3	Tue Dec  1 14:35:00 2026 a alice
4	Wed Dec  2 09:00:00 2026 a alice
$ atrm 4
$ atq
3	Tue Dec  1 14:35:00 2026 a alice
```

`at -c 3` prints the full script of job 3: the saved environment first, your commands at the end.

`atq` is the same as `at -l`, and `atrm` the same as `at -d` (or `at -r`). The `a` is the queue name. A normal
user sees only their own jobs, root sees all of them.

 (Side note: `batch` is a sibling of `at`: it takes commands the same way but runs them as soon as the system load drops below 1.5 (the default), which is handy for heavy jobs.)

Pending jobs are stored as files in the spool: `/var/spool/cron/atjobs/` on Debian, `/var/spool/at/` on RHEL.

### Who may use at: at.allow and at.deny

Same idea as cron, with one difference when neither file exists:

| Situation | Who can use `at` |
| --- | --- |
| `/etc/at.allow` exists | Only users listed in it |
| Only `/etc/at.deny` exists | Everyone except users listed in it (an empty file allows everyone) |
| Neither exists | Only root |

Debian ships an `/etc/at.deny` that lists system accounts like `daemon` and `www-data`. RHEL ships an empty one.

## systemd timers

On systemd machines, a **timer unit** can start any service unit on a schedule. It takes two files: the service
(what to run) and the timer (when). They share a name.

```ini {title="/etc/systemd/system/backup.service"}
[Unit]
Description=Back up /home

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
```

```ini {title="/etc/systemd/system/backup.timer"}
[Unit]
Description=Run the backup every night

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true

[Install]
WantedBy=timers.target
```

Then load and start the **timer** (not the service):

```bash
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
```

```console
$ systemctl list-timers
NEXT                        LEFT     LAST                        PASSED    UNIT                ACTIVATES
Tue 2026-12-01 15:00:00 CET 29min    Tue 2026-12-01 14:00:00 CET 30min ago dnf-makecache.timer dnf-makecache.service
Wed 2026-12-02 00:00:00 CET 9h left  Tue 2026-12-01 00:00:03 CET 14h ago   logrotate.timer     logrotate.service
Wed 2026-12-02 02:30:00 CET 11h left -                           -         backup.timer        backup.service

3 timers listed.
```

Add `--all` to also see inactive timers. Run the job now to test it with `sudo systemctl start backup.service`, and
read its output with `journalctl -u backup.service`.

### Calendar and monotonic timers

`OnCalendar=` takes `DayOfWeek Year-Month-Day Hour:Minute:Second`, where `*` means any and parts can be left out:

| `OnCalendar=` | Runs |
| --- | --- |
| `*-*-* 02:30:00` | Every day at 02:30 |
| `Mon..Fri 08:00` | Weekdays at 08:00 |
| `*-*-01 00:00` | First day of every month |
| `*:0/15` | Every 15 minutes |
| `hourly`, `daily`, `weekly`, `monthly` | Shortcuts (daily is 00:00) |

Check an expression before you trust it:

```console
$ systemd-analyze calendar "Mon..Fri 08:00"
  Original form: Mon..Fri 08:00
Normalized form: Mon..Fri *-*-* 08:00:00
    Next elapse: Wed 2026-12-02 08:00:00 CET
       (in UTC): Wed 2026-12-02 07:00:00 UTC
       From now: 17h left
```

Other useful `[Timer]` settings:

- `OnBootSec=10min`: run 10 minutes after boot.
- `OnUnitActiveSec=1h`: run again 1 hour after the last run started. These two are **monotonic** timers: relative
  times instead of clock times.
- `Persistent=true`: if the machine was off at the planned time, run as soon as it's back (like anacron).
- `RandomizedDelaySec=15min`: spread the start, so a thousand servers don't all hit the backup server at once.

### Quick timers with systemd-run

`systemd-run` creates a **transient** unit on the fly, with no files to write. With a timer option, it works like
`at`:

```console
$ sudo systemd-run --on-active=10min /usr/bin/touch /tmp/ten-minutes-later
Running timer as unit: run-r4f9c2a7d81e34b6c9a0d5e17f3b2c8a6.timer
Will run service as unit: run-r4f9c2a7d81e34b6c9a0d5e17f3b2c8a6.service
$ sudo systemd-run --on-calendar="*-*-* 18:00" --unit=evening-report /usr/local/bin/report
Running timer as unit: evening-report.timer
Will run service as unit: evening-report.service
```

Transient units disappear after a reboot. Cancel one with `sudo systemctl stop evening-report.timer`. Add `--user`
to run it in your own user session without sudo.

 (Side note: Users can have their own permanent timers too: put the unit files in `~/.config/systemd/user/` and use `systemctl --user`. They only run while you're logged in, unless root runs `loginctl enable-linger alice`.)

### cron or a timer?

| | cron | systemd timer |
| --- | --- | --- |
| Setup | One line | Two unit files |
| Logs | Mail, or your own redirect | Automatically in the journal |
| Missed runs | Lost (unless anacron) | `Persistent=true` catches up |
| Extras | | Dependencies, resource limits, random delay, run on boot |
| Exists on | Every Unix | systemd systems only |

Both are fine. Many distributions now ship timers for their own jobs (`logrotate.timer`, `fstrim.timer`,
`dnf-makecache.timer`, `apt-daily.timer`), so expect to read both.

## Exam checklist

- Crontab fields: minute, hour, day of month, month, day of week (0 and 7 are Sunday). Know `*`, `,`, `-` and `*/n`.
- `crontab -e`, `-l`, `-r`, `-u user`. User tables live in `/var/spool/cron/` (`crontabs/` subfolder on Debian).
- `/etc/crontab` and `/etc/cron.d/*` have an extra **user** field before the command. User crontabs don't.
- Scripts in `/etc/cron.{hourly,daily,weekly,monthly}/` are run by `run-parts`: they must be executable (and on Debian, have no dot in the name).
- `cron.allow` exists: only those users. Otherwise `cron.deny` lists who's blocked. Same for `at.allow` and `at.deny`, but with neither file only root may use `at`.
- `at TIME` schedules once, `atq` lists, `atrm N` removes, `at -c N` shows a job. Needs `atd` running.
- A systemd timer `name.timer` starts `name.service`. Enable the timer, then check it with `systemctl list-timers`.
- `OnCalendar=` for clock times, `OnBootSec=`/`OnUnitActiveSec=` for relative ones, `Persistent=true` to catch up.
- `systemd-run --on-active=` or `--on-calendar=` creates a one-off transient timer without unit files.


## Byte check

1. Which crontab line runs `/usr/local/bin/report` at 08:30 on weekdays only?
   - **`30 8 * * 1-5 /usr/local/bin/report`** (correct)
   - `8 30 * * 1-5 /usr/local/bin/report`
   - `30 8 1-5 * * /usr/local/bin/report`
   The fields are minute, hour, day of month, month, day of week. `1-5` in the fifth field is Monday to Friday.

2. Both `/etc/cron.allow` and `/etc/cron.deny` exist, and `bob` is listed in neither. Can bob use `crontab`?
   - Yes, because he isn't in `cron.deny`
   - **No, because `cron.allow` exists and he isn't in it** (correct)
   - Only if `cron.deny` is empty
   When `cron.allow` exists it wins: only the users in it may use cron, and `cron.deny` is ignored.

3. You created `backup.service` and `backup.timer`. What starts the schedule, also after a reboot?
   - `systemctl enable --now backup.service`
   - **`systemctl enable --now backup.timer`** (correct)
   - `systemd-run backup.timer`
   You enable the timer. The timer then starts the service with the same name each time it fires.


