Cron Jobs: All You Need To Know

On Linux and other Unix systems, cron is a scheduler tool that enables you to set up automated tasks known as “cron jobs”. Tasks don’t need to be executed over and over again when you generate cron jobs, which can lead to better web development and improved management efficiency. Common examples of a cron job are automating file downloads (to back up important documents) and monitoring servers. But cron jobs go much deeper than this, and it can be a complex topic to explore, which is why we’ve written this guide. Read on as we cover cron job basics (from syntax to permissions), examples of cron commands, and helpful tips.  

Cron Jobs Explained

Cron jobs are automated tasks set up with cron, a popular scheduler tool on Linux and other Unix systems. Using cron jobs is helpful for protecting against human error and boosting efficiency, as they eliminate the need to complete tasks manually again and again. Cache clearance, server monitoring, and software updates are common cron jobs.

How Does a Cron Job Function?

Cron is a process running in the background continuously, without your control, to perform a wide range of tasks. This type of program is known as a “daemon”, and it is typically put into action by particular conditions or events. Cron commands, which run at certain times, are located in cron files. By default, the configuration file for crontab (cron table) is /etc/crontab. However, system administrators are the only users able to modify crontab files, but as more than one admin is allowed on Unix-like systems, you can still set up your own files to schedule particular jobs. For example, you may use cron jobs to automate monitoring of disk space and system maintenance periodically. The convenience of cron jobs means they’re fantastic for machines running round the clock, such as virtual private servers. System administrators often use cron job scheduling, and web developers frequently take advantage of it too. That might involve configuring multiple cron jobs to create website backups automatically at a specific time each night and clear the cache once per week. It’s a streamlined and flexible way to complete repetitive tasks. However, despite that, cron jobs do have some drawbacks. For instance:
  • Cron jobs lack a function for automatically retrying failed tasks. If a certain task fails, it won’t be reattempted when it’s next scheduled to run as cron is intended to operate according to a specific plan. As a result, cron can be a poor choice for handling incremental jobs.
  • The minimum interval between cron jobs is fixed at one minute, nothing less.
  • Crontab is unable to read environment variables from multiple files that contain the necessary configuration data for running certain apps correctly.
  • You must reset missed jobs manually, as administrators are unable to allocate cron jobs to more than one computer on the same network. If a machine running cron stops working, the tasks scheduled won’t be executed, and you’ll need to do a manual reset for those missed jobs.
Still, these issues don’t stop cron from being a fantastic way to schedule repetitive jobs at particular times. Ultimately, you may want to try a different scheduling solution for automating a one-off job, though. It’s always important to check that your script is working properly before you create cron jobs. Open the relevant file in your web browser via URL or execute it with SSH, whichever suits the script type. If you can’t get either way to work, though, you may need to speak to your hosting provider for assistance.

Crontab: Understanding the Syntax

There’s one key factor you need to consider when planning cron jobs: the syntax and formatting must be correct for the script to run correctly. There are five fields in crontab syntax, containing the following potential values:
  • Minute: A specific minute within an hour (from 0 to 59) that a command will run at.
  • Hour: The hour that the command is scheduled to run at, using a 24-hour format (0 to 23).
  • Day of the month: The date within a month that you want the command to run on, from 1 to 31.
  • Month: The month that you want a command to run in, from January to December (1 to 12).
  • Day of the week: The day in a week that you want to run a command on, represented as 0 to 6 (for Sunday to Saturday). However, Sunday is represented by a 7 in certain systems.
You may be unable to fill these fields if you don’t have a value for them, so you’ll need to use an asterisk. For example, when scheduling a cron job to run the root/backup.sh script each Wednesday evening at 8:20, you could use the following command: 20 20 * * 3 rootbackup.sh  Here, the two “20”s represent the time (8.20 pm), while the asterisks in the Date and Month fields represent all possible values to ensure the job runs each Wednesday, no matter what the date or month. The “3” signifies Wednesday (if 0 is Sunday). With this command in place, the task will be completed as per the schedule each week. Not sure about writing cron syntax manually? Don’t worry — you can take advantage of free tools (such as Crontab.guru and Crontab Generator) to produce the necessary numbers for your command. As well as the syntax, you also need to know the cron job operators to change the values in all fields. Using the following operators correctly in every crontab file is vital to make sure your commands are executed properly:
  • Hash (#): A day-of-the-week operator that uses numbers from 1 to 5 to specify certain days within a month. For example, 2#3 signifies the third Tuesday of the month.
  • Asterisk (*): The asterisk represents all possible field values. You could enter an asterisk into the Hour field to ensure a cron job runs each hour, for instance.
  • Hyphen (-): You can use a hyphen to specify a value range: to schedule a cron job to run from October to December, for example, you could enter 10-12 in the Month field.
  • Comma (,): This operator is used when listing more than one value. If you wanted to schedule a cron job to run each Tuesday and Thursday, you would type 2,4 in the Day of the week field.
  • Separator (/): Separators divide values: enter */8 in the Hour field to schedule a cron job every eight hours.
  • Question mark (?): You can use this operator to enter no definite values in the Day of the week and Day of the month fields. The daemon’s activation time usually replaces this.
  • Weekday (W): This specifies the nearest weekday from a certain time. For example, if October starts on a Sunday, typing 1W into the Day of the month field will execute the command on the next day, even though that will be the third of October.
  • Last (L): This operator is entered into the Day of the week and Day of the month fields to specify the last day in a month (such as 5L in the Day of the week field to signify the last Friday).

Cron Examples

Now that we’ve explored the basics of cron jobs, we’ll share some helpful examples of how to use them. However, while cron delivers outputs to your local email address automatically, you can put >/dev/null 2>&1 into commands to stop receiving the emails. For example: 1 6 * * * /root/backup.sh >/dev/null 2>&1  But if you want to direct output to a particular email address, enter MAILTO and the relevant address: MAILTO=”[email protected]1 6 * * * /root/backup.sh >/dev/null 2>&1 We’ve created the following list of cron job command examples for system management:
Command Function
2 2 * * 4 /root/backup.sh Run a backup each Thursday at 10pm.
10,20 * * * /root/backup.sh Run a backup daily at 10am and 8pm.
0 7 5 */3 * /home/user/script.sh Run a quarterly job on the fifth day of a month at 7am.
0 * * * 2 /root/clearcache.sh Perform a cache wipe hourly on Tuesdays.
* * 31 10 * /root/backup.sh Run a backup each minute on October 31st.
1 7 * * 6 * /root/backup.sh Run a backup at 5pm every Saturday.
*/5 * * * * /root/backup.sh Run a backup every 5 minutes.
20-59/10 13 * * * /root/clearcache.sh Clear the cache every 20 minutes at 1pm, starting at 1:10 pm.
* * * * * /scripts/script-one.sh; /scripts/script-two.sh Compile several tasks into just one cron job. Helpful for configuring a number of tasks to execute simultaneously.
* * * 5,1,4 * /scripts/monitor.sh Run monitoring each minute in May, January, and April.
0 * * * * /root/backup.sh Set up an hourly backup.
0 6 1-7 * 1 /scripts/script.sh Run a script on the first Monday of every month at 6am.
@reboot /root/clearcache.sh Wipe the server cache whenever you switch the system on.
0 0 2,18 * 2 /scripts/script.sh Run a script each Tuesday, from the 2nd to the 18th of each month, at midnight.
0 9 * * 4 /root/backup.sh Run a backup each Thursday at 9am.
0 7 5,10 * * /scripts/monitor.sh Run monitoring on the 5th and 10th of each month at 7am.
@hourly /scripts/monitor.sh Run monitoring on an hourly basis.
0 8 * * * /scripts/monitor.sh Run a monitoring script at 8am once per day.
0 16 4 * * /root/clearcache.sh Wipe the cache on the fourth day of the month, each month, at 4pm.
0 9 1 12 * /root/backup.sh Run a backup at 9am on each December 1st.
0 5 10 * * /root/clearcache.sh Wipe the cache at 5am on the 10th of each month.
*/25 * * * * /scripts/monitor.sh Run monitoring every 25 minutes.

What Are Special Strings?

If you want to plan cron jobs at specific time intervals without defining the values exactly, you can use special strings. They’re pretty simple to write: just enter a phrase beginning with an @ symbol. The following special strings can be helpful when writing commands:
  • @reboot: Used to run a cron job once while a system is starting up.
  • @weekly: Used to schedule tasks once per week on Sundays at midnight.
  • @hourly: Used to run cron jobs once per hour.
  • @monthly: Used to schedule a task to run once on the first day of the month throughout the year.
  • @daily: Used to run a task at midnight daily (you can also use @midnight for this).
However, take care when scheduling cron jobs for alternative time zones to avoid misconfigurations.

Setting Permissions for Cron Jobs

You must set the correct permissions for the cron files on your system to run their jobs. To set permissions, you can make or modify cron.allow and cron.deny files. When /etc/cron.allow exists, it must contain a username allowed to execute the cron job automation. But if your system has /etc/cron.deny with a username, that account will be unable to utilize cron.

Running Cron Jobs

Let’s move onto the process of scheduling cron jobs: typing commands into a shell program on a Linux system. Cron is typically already installed as standard in Linux distros, but if it’s not, you’ll need to execute the necessary installation command for your package manager. For Ubuntu with apt, use the following command: sudo apt install cron  We should explain the configuration files here, before moving on to basic cron job tasks. There are two files: system crontab and user crontab. The system crontab file schedules important cron jobs, across the whole system, that can only be edited by users with root privileges. The user crontab file is for making and modifying cron jobs that apply at the user level only. You’ll need to give the current user root privileges, if they don’t have them already, to modify the system crontab file.

Generating a Crontab File

To edit a crontab file that already exists, type the snippet below into the command line. However, the command will automatically make a new one if your system doesn’t have it. crontab -e  The first time you input this snippet, you will be asked which text editor you want to use to modify the file (e.g. vi). You can enter other commands or change existing commands in a text editor.

Deleting Scheduled Tasks

Use the following command to remove all tasks scheduled in crontab entries and begin from the start: crontab -r  You can also use the crontab -i command if you want a confirmation option before the crontab is deleted.

Gaining Root Access

Restrictions on user privileges mean that certain commands require root permissions to run. If you want to grant yourself root access, put sudo su at the start of the relevant command. Furthermore, you can put cron jobs into the etc/cron.d directory for storing automatic installation and update scripts. You’ll need to have root access and follow run-parts naming conventions to put them into this directory, On the other hand, you can relocate cron job scripts in hourly, daily, weekly, or monthly directories as needed. For example, use /etc/cron.hourly/ to run a script once each hour or /etc/cron.monthly for once each month.

Viewing Active Schedule Tasks

Want to check out all the tasks that are active and scheduled in your Linux system? Use the following: crontab -l  For systems with more than one user, enter the following command as a superuser to see their crontab file lists:  crontab -u username -l

Cron Jobs in Plesk

Plesk Obsidian is a comprehensive web hosting and server management platform designed to simplify the administration of websites, databases, email services, and more. It provides users with an intuitive graphical interface, automation tools, and extensive security features, making it ideal for web professionals managing hosting environments across various operating systems. If you use Plesk on your server and there is a necessity to execute scripts at predetermined intervals, employ the server’s task scheduling function. This automates script execution according to the specified schedule.
  1. Log into Plesk
  2. Navigate to Domains > mydomain.com > Scheduled tasks OR Tools & Settings > Scheduled Tasks
  3. Click Add task and set specify Run parameter to Cron style.
  4. Fill in the Run text field with cron-style time syntax, e.g.: * */2 * * *
  5. Fill in the Command text field with the cron command, e.g.: /usr/bin/echo "hello world"

Conclusion

If you use a Unix-based system, you can leverage the cron daemon to generate automation scripts to schedule tasks. The tasks automated with cron, such as system updates or monitoring, are referred to as &ldquocron jobs”. You need to type a crontab command into your system’s cron file to automate tasks. Commands contain the execution script and five asterisks representing the job’s activation time. Modify these asterisks’ values and change the time with the operators. When you’re ready to run cron jobs, use Terminal, an SSH client, or a different CLI program with root permission to connect your Linux system. Next, generate a crontab file and use a text editor to add the script. And that’s it!

No comment yet, add your voice below!

Add a Comment

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

GET LATEST NEWS AND TIPS

  • Yes, please, I agree to receiving my personal Plesk Newsletter! WebPros International GmbH and other WebPros group companies may store and process the data I provide for the purpose of delivering the newsletter according to the WebPros Privacy Policy. In order to tailor its offerings to me, Plesk may further use additional information like usage and behavior data (Profiling). I can unsubscribe from the newsletter at any time by sending an email to [email protected] or use the unsubscribe link in any of the newsletters.

  • Hidden
  • Hidden
  • Hidden
  • Hidden
  • Hidden
  • Hidden

Related Posts

Knowledge Base