Cron Jobs - What? Why? How?
What are cron jobs?1
Cron jobs are, at a very atomic level, your servant. You ask them to do something at specific intervals of time or at a specific time or date or day and they do it accordingly.
Now as this servant is not artificially intelligent you have to line-by-line teach it what to do, for which you have to write scripts for the cronjob to execute.
Why should anybody be using cron jobs?
- Cronjobs are mostly used for server maintenance, that is, to do tasks like clearing folders,
making hourly calculations and other repetitive tasks that can be automated. Some common uses would be -
- Create database backup every night
- Calculate “trending articles”
- Automatically send birthday messages to users in the database
- It’s great for productivity and gives you a sense of control over your system, you can automate almost any repetitive task that you do on your laptop like deleting files from trash, automatically download the latest Dragon Ball episode, set up alarms. I personally have a job running every morning at 6 which sets the system volume to 100 and starts playing random music on youtube.
How to cron?
Like all cool things, this one too has to be done using the terminal on your *nix system. The name of the program
that lets you access and change the jobs is
crontab. The two basic functions2 of crontab are -
- crontab -l : Lists the contents of the cron tab which basically are all the jobs you’re running.
- crontab -e : Opens a text editor on the terminal with the crontab so that you can remove/comment out/add cron jobs.
Format of a cron job
* * * * * path_to_script * * * * * /usr/bin/php path_to_php.php * * * * * /usr/bin/python path_to_php.py
There are 5 specifiers of different units of time followed by path to a file which should be executed by the job.The specifiers are -
I’ll do a follow up post which will be more detailed and will have some example cron scripts which I’ve used in real life projects. Till then you can easily generate the time specifiers using this bomb website called crontab.guru
Formal Definition - The software utility Cron is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. ↩︎
These are one of many options that
crontabprovides, but these are enough for basic use. ↩︎