How to Create a Cron Job
In Unix operating systems, Cron is a built in utility. If you are on a Mac, you can use the crontab in your terminal to view current cron jobs and add a new cron job.
#To view current cron jobs
crontab -l#To create new cron jobs
Following the crontab -e command, you will be redirected to the cron table editor. To insert a new cron job click the letter “i” on your keyboard to enable insert.
The below cron job is adding the word “Hello, World!” every minute, of every hour, of every day, of every month, for every day of the week to a test.txt file.
Code Ran: * * * * * echo ‘Hello, World!’ >> test.txt
To save the cron and quit out of the cron table use the following command
To ensure that your cron was created successfully you can use crontab -l and cat test.txt. Crontab-l will show our cron as a current cron job and cat test.txt will show the text added to our test.txt file from the cron job.
How to Alter Time Fields
Before entering your first cron job it is important to understand how to set the time for when you would like your Cron job to run. The time fields are customizable and can fit many different needs, see below for some examples.
#Every Sunday at 5:30AM
30 5 * * 0 echo 'Hello'' >> /tmp/test.txt#Every 15 minutes
*/15 * * * * echo 'Hello'' >> /tmp/test.txt#Workdays at 5:00PM
0 17 * * 1-5#The 1st & 10th at Midnight
0 0 1,10 * * echo 'Hello'' >> /tmp/test.txt
To remove cron jobs
To remove cron jobs, simply type the following command into your terminal.
Cron jobs are a powerful tool for developers and allow for the automation of many repetitive tasks. I hope this walk-through will encourage you to try cron jobs and implement them in your upcoming projects both professional and personal.