ubuntu, updated

Cronjobs

How cron works, how to list, create and delete cronjobs, the time syntax, and which user a job should run as.

How it works

The cron service wakes up every minute, reads all job lists (crontabs) and runs the jobs whose time matches. Each job runs as a specific user, with a minimal environment (short PATH, no aliases, no .bashrc).

There are two kinds of crontabs:

User crontabSystem crontab
Where/var/spool/cron/crontabs/USER (don’t edit directly)/etc/crontab and files in /etc/cron.d/
Edit withcrontab -ea text editor, as root
Runs asthat userthe user named in each line
Good forpersonal jobsserver jobs you deploy and version

Plus folders for scripts without a schedule line: /etc/cron.hourly/, cron.daily/, cron.weekly/, cron.monthly/. Drop an executable script in there (file name without dot or extension!) and it runs at that interval as root.

The time syntax

┌───────── minute        0-59
│ ┌─────── hour          0-23
│ │ ┌───── day of month  1-31
│ │ │ ┌─── month         1-12
│ │ │ │ ┌─ day of week   0-7 (0 and 7 = Sunday)
│ │ │ │ │
* * * * *  command
ScheduleMeans
*/5 * * * *every 5 minutes
0 * * * *every hour, on the hour
30 2 * * *daily at 02:30
0 6 * * 1-5weekdays at 06:00
0 3 1 * *1st of every month at 03:00
@rebootonce, after every boot
@daily, @weeklyshortcuts for midnight / Sunday midnight

Times are in the server’s time zone (timedatectl). Not sure? crontab.guru translates any line into words.

Cheat sheet

WhatCommand
List my cronjobscrontab -l
Edit my cronjobscrontab -e
List / edit another user’ssudo crontab -l -u anna / sudo crontab -e -u anna
Delete all my cronjobscrontab -r (no confirmation!)
Delete one jobcrontab -e and remove the line
System jobscat /etc/crontab; ls /etc/cron.d/ /etc/cron.daily/
List all user crontabssudo ls /var/spool/cron/crontabs/
Did it run?journalctl -u cron --since today

A good cron line

# m  h  dom mon dow  user    command
30   2  *   *   *    backup  /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1

Should jobs get their own user?

Yes, for anything that is not real admin work. Run a job with the least rights it needs:

sudo adduser --system --group --no-create-home backup
sudo chown backup:backup /srv/backups

Then use the /etc/cron.d/ line above with backup as user. If the job needs one root command, allow exactly that with a sudoers rule.

Alternative: systemd timers

Timers do the same job, with logs in the journal, no missed runs after downtime (Persistent=true) and resource limits. Worth it for important jobs. See all timers:

systemctl list-timers

A timer is a .timer file next to a .service file with the same name. Start with cron. Move to a timer when you need its extras.

§ home
~/knubertus/home/
1,1 Top