How to add Cron jobs in Linux & MacOS

Context

Quiet often you will face a need to run tasks, custom scripts, cleanups, firing background processes for your application, rotate logs and more on a recurring schedule.

I personally use cron to backup databases, automatically update SSL certificates using Let's Encrypt, and to clean up /tmp folder.

Unix provides us with Cron service which reads the crontab file and looks up few other directories such as /etc/cron* and /var/spool/cron. It then processes given commands for you in the background.

Cron is managed by crontab command which you can look up to its man page for more information. By using crontab COMMAND , we will be able to edit the crontab FILE which then the cron SERVICE will read and process.

$ man crontab

How to edit crontab file

To edit run crontab -e which will prompt an empty text file in case you don’t have any cron jobs set up.

You can then type in your schedule followed by a command that needs to be run as below:

0 16 * * * /home/myscripts/somerecurringscript.sh

[MINUTE] [HOUR] [DAY] [MONTH] [DAY OF THE WEEK] COMMAND

Save and exit.

Now every day at 4 PM, Cron service will run the given command. Please, keep in mind that if your computer is shut down, it will not run the command and will do so when the machine is turned on again.

Few extras

If your given command generates something for Standard Output or exists with an error code, it will try to email you. To opt out from emails, you can redirect the output somewhere, such as /dev/null which will be discarded instantly.

0 16 * * * /home/myscripts/somerecurringscript.sh > /dev/null 2>&1

You can also use redirection when you would like to store the output inside some log file.

0 16 * * * /home/myscripts/somerecurringscript.sh > /var/log/precious_log_file

Tools to use for managing Cron jobs in Ruby

If you would like to manage Cron jobs in your Ruby projects at application level at much higher abstraction, you can use a gem such as Whenever which has a friendly DSL to create and schedule recurring tasks.

every 3.hours do # 1.minute 1.day 1.week 1.month 1.year is also supported
  # the following tasks are run in parallel (not in sequence)
  runner "MyModel.some_process"
  rake "my:rake:task"
  command "/usr/bin/my_great_command"
end

every 1.day, at: '4:30 am' do
  runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end

every 1.day, at: ['4:30 am', '6:00 pm'] do
  runner "Mymodel.task_to_run_in_two_times_every_day"
end

every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
  runner "SomeModel.ladeeda"
end

every :sunday, at: '12pm' do # Use any day of the week or :weekend, :weekday
  runner "Task.do_something_great"
end

every :day, at: '12:20am', roles: [:app] do
  rake "app_server:task"
end

That’s it for today, now create a few tasks for good old Cron and let it do its job.