Run cron job in Linux

A cron job tasks can be scheduled to run by minutes, hours, day of the month, months, day of the week, or any combination of these too.

Cron jobs can be used to automate system administration tasks, such as backing up data or databases or files, sending emails, checking disk space usage, and so on.

Crontab is a command and a file too where you can define the schedule of cron jobs. It can be created, viewed, modified, and removed, like other files.

In the crontab file, there are six fields separated by a space followed by the command to be run:

* * * * * any-command-can-be-here
^ ^ ^ ^ ^
| | | | |     Only are numbers allowed as a value
| | | | |     -------
| | | | ----- Day of week (0-7) (0=Sun or 6=Sat), or 7 can be counted as Sunday as well.
| | | ------- Month (1-12)
| | --------- Day of month (1-31)
| ----------- Hours (0-23)
------------- Minutes (0-59)
  • * The asterisk operator means any value is allowed. For example, If you add the asterisk symbol in the Hour field, it means the task will be performed every Hour.
  • - The hyphen operator can be used to specify a range of values. For example, If you set 1-3 in the Day of the week field, the task will run every weekday (From Monday to Wednesday).
  • , The comma operator values can be defined as a list of values for repetition. For example, if you have 2,4,6 in the Hour field, the task will run at 2 am, 4 am and 6 am. This Operator can contain ranges 2-6,8,10,12-15 as a single value without space. Instead of using a comma operator or range of values, you can also use the asterisk-slash-value operator. For example, */20 will run every 20 minutes and give you the same result as range and comma operators were giving.

You can also specify which user can run the cron job.

* * * * * username command

Rub the crontab -e command to edit the crontab file, or create one if it doesn’t exist.

To run a cron job every 20 minutes, add the following line in your crontab file.

*/20 * * * * root /home/root/

To run a cron job every 5 Hours, add the following line in your crontab file.

* */5 * * * root /home/root/

To run a cron job every Minute, add the following line in your crontab file.

* * * * * ubuntu /home/ubuntu/

Feel free to visit my YouTube Channel to learn more about Tech World in video form.