There’s been quite a few projects recently where I’ve found myself doing tedious things that can easily be automated. Enter Cron, the time-based job scheduler.
Once or twice a week I find myself updating/rebuilding my Jekyll Site because it displays my Medium RSS feed as a Blog page. As the site is static, I need to re-build it every time I publish something new. It’s not an issue as it’s only a few commands, but sometimes I forget and weeks can go by without updating my site. Writing a Cron job is so stupidly easy, you’ll find yourself automating pretty much every mundane task you do.
Writing a Cron Job
#bash$ env EDITOR=nano crontab -e #opens nano in your terminal, with your crontab open.
You should see something like this now, after running the above command.
Ok so not exactly like this, as this contains my cron job, but it should be a nice empty text file. For my purpose, I decided to create an executable file with the commands and then get cron to run that, however you can run the commands inside here, it’s just tidier to write a script for it.
Cron Time Intervals
Cron works by executing your commands at a determined time, whether that be weekly on a Monday at 2pm or on the 15th of each month. The * * * * * at the start each determine a different time scale.
- 1st character, * — Minute of the Day
- 2nd character, * * — Hour of the Day
- 3rd character, * * * — Day of the Month
- 4th character, * * * * — Month of the Year
- 5th character, * * * * * — Day of the Week (0–7, Sunday is both represented by a 0 and 7)
You’ll notice in my example, I decided to execute every week on a Sunday.
Here’s another example if you want to run a job at 6:30 every Tuesday.
#nano30 18 * * 2 yourcommand #execute every Tuesday at 18:3045 07 10 * * yourcommand # execute every 10th day of the month at 07:4520 15 * * 3 yourcommand # execute at 15:20 every Wednesday
Let’s make this a little easier and add some shortcut commands to our .bashrc or .zshrc (depending on what you’re using).
Using the alias command we can shortcut a long command to something a little easier to remember and type.
#.bashrc or .zshrcalias newcron="env EDITOR=nano crontab -e" #open a new crontab
alias cronjobs="crontab -l" # list our cronjobs
Now you’re set to automate whatever you want!
As always, thanks for reading, hit 👏 if you like what you read and be sure to follow to keep up to date with future posts.