Cheatsheet: Crontab
Crontab is a very very useful piece of software available on (more or less) every Linux system. It can be used to periodically run a command/script/application which is, especially in the server-space, really useful.
Thankfully Crontab is easy to configure and use. Just enter crontab -e
to edit the Crontabs for your current user, if you want to edit the systemwide Crontabs, use sudo crontab -e
, which will also allow you to select what user the command should be executed by, which includes root. The rest of this tutorial is made for the non-sudo command, they are really similar though, the only real difference is that you can specify which user the command should be run by.
After executing that command, you may have to select your editor of choice and then you’re presented with a file like this:
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
This file actually gives you a good idea on how to use it. In order to add a new command, create a new line that looks like this:
<minute> <hour> <day of month> <month> <day of week> <command>
So, for example, if you want to run your backup-script automatically every Sunday at 2am, you just write this line:
* 2 * * 0 cp /home/host13/* /mnt/Backup/
Or to refresh your Nextcloud cron every 5 minutes:
*/5 * * * * /usr/bin/php -f /var/www/cloud/cron.php
If you need help with writing those commands, I recommend you checkout crontabgenerator. There you can generate them online with dials and buttons.
There’s also another way of writing those entries, instead of a time you can use @reboot
. Those will then be executed when the system boots. If your script doesn’t stop, you can add a &
at the end of the command, so that it doesn’t halt the boot process.
@reboot /home/host13/skyNet/start.sh &
So in short, Crontab is a really useful tool for automation of server stuff and I recommend that everyone should at least know how to use it.