Home / Cron Job: A Comprehensive Guide for Beginners

Cron Job: A Comprehensive Guide for Beginners

cron job

It can be tedious to repeat the same task over and over. Cron jobs allow users to automate tasks on a virtual private server or any Unix-like operating system by scheduling them. This saves time and allows users to focus on more important tasks.

In this comprehensive beginner’s guide, you will learn the fundamentals of cron jobs, including their types, syntax, special strings, and permissions. You will be able to use cron jobs to schedule tasks more efficiently by the end of this article.

What is a Cron Job?

Cron is a utility program that allows users to enter commands for repeating tasks at a set time. Cron jobs are tasks that are scheduled in cron. Users can choose which tasks they want to automate and when they want them to be completed.

Cron is a daemon, which means it runs in the background and performs non-interactive tasks. Background processes such as Services, which work similarly to the cron daemon, may be familiar in Windows.

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

A cron file is a simple text file that contains commands that will run on a regular basis at a predetermined time. /etc/crontab is the default system cron table or crontab configuration file, which is found in the crontab directory /etc/cron.*/.

The system crontab file can only be edited by system administrators. Unix-like operating systems, on the other hand, allow for multiple administrators. Each individual can create a crontab file and write commands to run jobs at any time.

Users can use cron jobs to automate system maintenance, disk space monitoring, and backup scheduling. Cron jobs are ideal for computers that operate 24 hours a day, seven days a week, such as servers, due to their nature.

Cron jobs are primarily used by system administrators, but they can also be useful for web developers.

As a website administrator, you can use cron jobs to backup your site every day at midnight, check for broken links every Monday at midnight, and clear your site cache every Friday at noon.

However, cron, like any other program, has limitations that you should be aware of before employing it:

  • 60 seconds is the shortest time between jobs. You won’t be able to repeat a job every 59 seconds or less using corn.
  • On a single computer, everything is centralized. Cron jobs cannot be distributed across a network of computers. The scheduled tasks will not be executed if the computer running cron crashes, and the missed jobs will have to be run manually.
  • There is no automatic retry mechanism. Cron is programmed to run at predetermined intervals. If a task fails, it will not run again until the next time it is scheduled. As a result, cron is ineffective for incremental tasks.

Despite these drawbacks, cron is an excellent solution for simple tasks that must run at a specific time and at least 60-second intervals.

Basic Cron Job Operations

This tutorial will show you how to use a shell program like Bash on Linux or another Unix-like operating system to schedule cron jobs.

VPS hosting from SeiMaxim is based on the Linux operating system. As a result, learning how to schedule cron jobs will help you be more productive as a VPS administrator. PuTTY SSH can be used to access the VPS command line.

It’s necessary to understand the different cron job configuration files before proceeding with the basic cron operations:

The crontab file for the system. It can be used to schedule system-wide, critical jobs that can only be changed by root users.

crontab is a user. Users can use this file to create and edit cron jobs that only apply to them.
Make sure the current user has root privileges before editing the system crontab.

The following are some of the basic tasks that cron can complete:

To create or edit a crontab file, enter the following into the command line:

  • crontab -e

If no crontab files are found in your system, the command will automatically create a new one. crontab -e allows you to add, edit, and delete cron jobs.

You’ll need a text editor like vi or nano to edit a crontab file. When entering crontab -e for the first time, you’ll be asked to choose which text editor you want to edit the file with.

To see a list of active scheduled tasks in your system, enter the following command:

  • crontab -l

If your system has multiple users, you can view their crontab file lists by entering the following command as a superuser:

  • crontab -u username -l

You can also easily edit other users’ scheduled jobs by typing the following crontab command:

  • sudo su crontab -u username -e

To give yourself root privileges, append sudo su to the beginning of the command. Some commands, including this one, can only be executed by root users.

Lastly, to delete all scheduled tasks in your crontab file and start fresh, type the following command:

  • crontab -r

Alternatively, the following command is the same as crontab -r, except it will prompt the user with a yes/no option before removing the crontab:

  • crontab -i

In addition to crontab, the root user can also add cron jobs to the etc/cron.d directory. It’s most suitable for running scripts for automatic installations and updates.

Keep in mind that the user adding cron jobs to this directory must have root access and conform to run-parts naming conventions.

Alternatively, a root user can move their scripts into the following directories to schedule their execution:

/etc/cron.hourly/ – Run all scripts once an hour
/etc/cron.daily/ – Run once a day.
/etc/cron.weekly/ – Run once a week.
/etc/cron.monthly/ – Run once a month.

First, you’ll need to get familiar with the syntax and formatting of cron. Setup of cron jobs may be impossible otherwise.

There are five fields in the crontab syntax that can have the following 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.

Don’t leave any of the fields blank.

If, for example, you want to set up a cron job to run root/backup.sh every Friday at 5:37 pm, here’s what your cron command should look like:

37 17 * * 5 root/backup.sh

37 and 17 are used to represent 5:37 p.m. These two asterisks represent all possible values for Day of the month and Month. This means that the task must be repeated at some point in the future, regardless of the date or the month in which it is performed. Lastly, the number 5 denotes Friday. The location of the task is then given in the form of a set of numbers.

Use free tools like Crontab Generator or Crontab.guru to get exact numbers for the time and date you want for your command if you don’t feel confident writing the cron syntax manually.

Cron job operators are essential if you want to set the right time for your cron command. They allow you to choose which values to enter in each field. All crontab files must be written with the proper operators.

  • Asterisk (*). Use this operator to signify all possible values in a field. For example, if you want your cron job to run every minute, write an asterisk in the Minute field.
  • Comma (,). Use this operator to list multiple values. For example, writing 1,5 in the Day of the week field will schedule the task to be performed every Monday and Friday.
  • Hyphen (-). Use this operator to determine a range of values. For example, if you want to set up a cron job from June to September, writing 6-9 in the Month field will do the job.
  • Separator (/). Use this operator to divide a value. For example, if you want to make a script run every twelve hours, write */12 in the Hour field.
  • Last (L). This operator can be used in the day-of-month and day-of-week fields. For example, writing 3L in the day-of-week field means the last Wednesday of a month.
  • Weekday (W). Use this operator to determine the closest weekday from a given time. For example, if the 1st of a month is a Saturday, writing 1W in the day-of-month field will run the command on the following Monday (the 3rd).
  • Hash (#). Use this operator to determine the day of the week, followed by a number ranging from 1 to 5. For example, 1#2 means the second Monday of the month.
  • Question mark (?). Use this operator to input “no specific value” for the “day of the month” and “day of the week” fields.

Cron Jo Special Strings

Special strings are used to schedule cron jobs at time intervals without the user having to figure out the logical set of numbers to input. To use them, write an @ followed by a simple phrase.

Here are some useful special strings that you can use in commands:

  • @hourly. The job will run once an hour.
  • @daily or @midnight. These strings will run the task every day at midnight.
  • @weekly. Use this to run jobs once a week at midnight on Sunday.
  • @monthly. This special string runs a command once on the first day of every month.
  • @yearly. Use this to run a task once a year at midnight on January 1st.
  • @reboot. With this string, the job will run only once at startup.

Cron Syntax Examples

We’ll go over some examples now that you’ve seen what proper cron syntax looks like.

The cron output will be sent to your local email account automatically. If you don’t want to receive emails, you can use the following command: >/dev/null 2>&1

0 5 * * * /root/backup.sh >/dev/null 2>&1

The output can be sent to a specific email address by putting MAILTO after the email address. Here’s a case in point:

MAILTO="myname@seimaxim.com"
0 3 * * * /root/backup.sh >/dev/null 2>&1

To learn more about the cron syntax, consider running the following examples:

0 0 * * 0 /root/backup.sh Perform a backup every Sunday at midnight.
0 * * * 1 /root/clearcache.sh Clear the cache every hour on Mondays.
0 6,18 * * * /root/backup.sh Backup data twice a day at 6am and 6pm.
*/10 * * * * /scripts/monitor.sh Perform monitoring every 10 minutes.
*/15 * * * * /root/backup.sh Perform a backup every 15 minutes.
* * 20 7 * /root/backup.sh Perform a backup every minute on July 20.
0 22 * * 1-5 /root/clearcache.sh Clear the cache every weekday (Monday to Friday) at 10pm.
0 0 * * 2 * /root/backup.sh Perform a backup at midnight every Tuesday.
* * * 1,2,5 * /scripts/monitor.sh Perform monitoring every minute during January, February, and May.
10-59/10 5 * * * /root/clearcache.sh Clear the cache every 10 minutes at 5am, starting from 5:10am.
0 8 1 */3 * /home/user/script.sh Make the task run quarterly on the first day of the month at 8am.
0 * * * * /root/backup.sh Create a backup every hour.
* * * * * /scripts/script.sh; /scripts/scrit2.sh Include multiple tasks on a single cron job. Useful for scheduling multiple tasks to run at the same time.
@reboot /root/clearcache.sh Clear cache every time you turn on the system.
0 8 1-7 * 1 /scripts/script.sh Run a script on the first Monday of each month, at 8 am.
5 4 * * 0 /root/backup.sh Create a backup every Sunday at 4:05 am.
15 9 1,20 * * /scripts/monitor.sh Perform monitoring at 9:15 pm on the 1st and 20th of every month.
@hourly /scripts/monitor.sh Perform monitoring every hour.
0 0 1,15 * 3 /scripts/script.sh Run a script at midnight every Wednesday between the 1st and 15th of every month.
15 14 1 * * /root/clearcache.sh Clear the cache on the first day of every month at 2:15 pm.
00 08-17 * * 1-5 bin/check-db-status Check database status every day from Monday to Friday every hour from 8 to 5 pm.
15 6 1 1 * /root/backup.sh Perform a backup every January 1st at 6:15am.
0 0 * * * /scripts/monitor.sh Run the monitoring script once a day at midnight.
0 0 15 * * /root/clearcache.sh Clear the cache at midnight on the 15th of every month.
* * * * 1,5 /scripts/monitor.sh Performing monitoring every Monday and Friday.

Cron Permissions

The following two files can be used to allow or deny access to the system’s cron file:

Permissions to run cron jobs should be granted to a specific user in /etc/cron.allow, if it exists.
In order to use cron jobs, the user must not be listed in /etc/cron.deny if cron.allow does not exist.

Conclusions

Setting up recurring tasks is a convenient way to avoid forgetting important tasks.

A great tool for system administrators and web developers is the use of cron jobs. You simply need to type in the correct commands and select a suitable execution time.

Use the correct command line syntax to schedule a cron job. Alternatively, you can use special strings to simplify the process. Make sure that the cron file can only be accessed by authorized users by assigning the correct permissions.

Leave a Reply