Cron - Linux Job Scheduler
A Linux sysadmin could automate multiple tasks using bash commands. But say, what if we want to run a certain script everytime we reboot? Or, backup our system every Tuesday at 12 a.m.? This is where
cron comes in handy.
cron allows a sysadmin to schedule these commands/programs/tasks to run at a certain time.
cron? cronjob? crontab?
Well, the names might seem a little bit overwhelming
for beginners. Basically...
cronis a program(daemon) that runs once the OS boots up.
- A cron job (schedule) is a command/program to be executed at a specified time.
crontab(cron table) is the file that contains the cron jobs to be executed.
crontabis the command for modifying cron jobs.
Creating a cronjob
crontab -e (
-e stands for edit) for the first time would prompt the user for a preferred text editor. We would choose
nano for now since it is the most user friendly for beginners.
no crontab for d3lt4 - 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 :
cron would then create a temporary
crontab along with the manual of creating cron jobs (TL;DR). Which actually comes down to this format.
To run a cron job on every reboot, we could use
@reboot at the time section. Remember that cron jobs are commands executed based on the users' table. Thus, it could only successfully execute commands that is within the priveleges of the user.
Logging has always been an issue for cron users due to logging settings turned off by default. But there are some tweaks to make logging feasible . cron actually keeps logs in /var/log/syslog, we could simply
grep cron logs from syslog via grep.
grep CRON /var/log/syslog
Or, we could just edit syslog's settings and write all cron logs in a cron.log file by uncommenting
nano /etc/rsyslog.d/50-default.conf sudo service rsyslog restart
This only logs the errors that occur within cron. If there was a syntax error within your command, you could redirect and append the output of stderr to a log file by adding a cron job. Make sure your script is executable by your user~
* * * * * /path/to/script.sh >> /path/to/log/script.log 2>&1 # redirect file descriptor 2 (stderr) to file descriptor 1 (stdout), the `&` is needed or else it would be interpreted as file name `1` instead of `stdout`
This post is inspired by Noob's Space.