Cron Schedule Syntax
Things to keep in mind to make your life easier in the long run.
1. Try not to run cronjobs as a user that might be temporary, i.e. a server admin that might not be there in 2 years, people rotate jobs.
2. Set the crons to run as a system user with the minimum required permission that the script needs, not root. Running a cronjob as root is stupid, unless absolutely required.
crontab -u <user> -e / crontab -u www-data -e
This will run the cronjob with permissions of Apache on Ubuntu.
3. DO NOT RUN AS ROOT. you will forget about it, at some point you or another admin will alter the script and it is running with permissions that can destroy things.
Create a file on every server in the same location that will not disappear if a user is removed. (/etc/THISSERVERSCRONJOBS.info) is fine. List all the cronjobs on the server, what they do, who wrote the scripts, what their primary purpose is, what will happen if they dont run on the set schedule.
If a server is a little loaded dont let a cron run every minute * * * * * is too common and easy.
For the minutes
*/2 will make it run every 2nd minute (50% reduction in server resource requirement for this script instantly)
*/5 every 5th minute, use this to balance a server where a cron is not needed every minute.
Balance all your crons like this so you dont get stupid spikes for no reason as all scripts try run at the exact same time every minute.
DO NOT SET CRONS UNDER YOUR PERSONAL USER if it is needed for server related tasks, even you might leave or another admin might see a problem or want to add a feature, they will not check you personal cronjobs.
A basic crontab entry looks something like this:
* * * * * /home/user/bin/somecommand.sh
| | | | | Command or Script to execute
| | | | Day of week(0-6 | Sun-Sat)
| | | Month(1-12)
| | Day of Month(1-31)
| Hour(0-23)
Min(0-59)
https://crontab.guru/ – this is just an awesome site to get the entry for a specific schedule.
Managing Crontab Entries
Once cron is running, it checks for crontab entries in the following files every minute:
- /etc/crontab
- /var/spool/cron/crontabs/$USER (where
$USER
is the currently logged-in user)
The first file, /etc/crontab, is a system-generated file containing shortcut commands designed to check for cron table entries in the following directories: /etc/cron.hourly
, /etc/cron.daily
, /etc/cron.weekly
, and /etc/cron.monthly
.
For the purpose of this article, you will concentrate on creating new crontab entries for your user.
You can achieve this by using the crontab
command. From the terminal, enter edit mode for your user’s crontab using the following command:
$ crontab -e
The first time you run this command, the OS should ask you what editor you would like to use with a little menu like this:
no crontab for user - using an empty one
Select an editor. To change later, run 'select-editor'.
1. /bin/nano <---- easiest
2. /usr/bin/vim.basic
3. /usr/bin/vim.tiny
4. /bin/ed
Choose 1-4 [1]: