How to setup cron to automate your Commands

Cron is a utility tool that allows you to enter commands for repeating actions at a set time. Tasks scheduled in cron are called cron jobs. You have the ability to set the schedule and choose which command you want to automate.

Cron is a daemon – a background process executing non-interactive jobs. In Windows, you might be familiar with background processes such as Services that work similarly to the cron daemon.

A daemon is always idle, waiting for a command that tells it to do something. Any machine on the network can run the command.

Beginner guide to use cron

Setup

To add a new crontab or edit existing crontab, run this command

crontab -e

To show the command of your crontab, run this command:

crontab -l

To remove all cron jobs for the current user:

crontab -r

Note: If you already use crontab -e and enter a schedule for your command but it does not show when you use crontab -l, you may want to manually add a file in the cronjob folder located in path /var/spool/cron/crontabs. To do that, you want to run these commands:

sudo su
nano /var/spool/cron/crontabs/<your_username>

Syntax

To create a cron job, you’ll need to understand cron’s syntax and formatting first. Otherwise, correctly setting up cron jobs may not be possible.

The crontab syntax consists of five fields with the following possible values:

  • Minute. The minute of the hour the command will run on, ranging from 0-59.
  • Hour. The hour the command will run at, ranging from 0-23 in the 24-hour notation.
  • Day of the month. The day of the month the user wants the command to run on, ranging from 1-31.
  • Month. The month that the user wants the command to run in, ranging from 1-12, thus representing January-December.
  • Day of the week. The day of the week for a command to run on, ranging from 0-6, representing Sunday-Saturday. In some systems, the value 7 represents Sunday.

Note: Don’t leave any of the fields blank.

Useful tip

If you don’t want to stress out checking the documentation on where the months or days are placed in the format. There is a website called Crontab Guru which tells you the exact time based on your inputs

https://crontab.guru/

Reference
https://www.hivelocity.net/kb/what-is-cron-job/
https://www.seobility.net/en/wiki/CronJob

Leave a Comment

Your email address will not be published. Required fields are marked *