How to Setup Cron Jobs in Linux to Schedule Tasks (Automation)

How to Setup Cron Jobs in Linux to Schedule Tasks (Automation). This blog is a detailed overview of Cron Jobs. So, without wasting much of your time, delve deep into it.

Doing the same thing continuously can become overwhelming. However, with the help of Cron Jobs, you can automate tasks on a virtual private server or any Unix like operating system. It saves you time and allows you to focus on more essential things.

Let’s continue with the article How to Setup Cron Jobs in Linux to Schedule Tasks (Automation).

What is Cron Jobs?

Cron is a utility program that enables you to input commands to schedule tasks continuously at a specific time. The tasks you schedule in cron are called Cron Jobs. Also, it allows you to determine the type of tasks you want to automate and the time for execution.

Cron is a background process that executes non interactive jobs. In Windows, the background processes are Services. It works similarly to the Cron Daemon. A cron file is a straightforward text file containing commands to run periodically at a specific time.

With the help of Cron Jobs, you can automate system maintenance, disk space monitoring, and schedule backups. Their nature makes it an appropriate choice for computers working 24/7, like servers. Mostly, system administrators use Cron Jobs, it is beneficial for web developers too. For example, a web administrator sets up Cron Job to automatically back up your site daily at midnight. It also checks broken links every Monday at midnight and clears your site cache every Friday at noon.

However, like every program, Cron constitutes some limitations that you should consider:

  • In Cron, the shortest interval between jobs is 60 seconds. Hence, it cannot repeat a job every 59 seconds or less.
  • Cron runs at a strictly specified time. So, if a task fails, it will not run until the next scheduled time, making it inappropriate for incremental tasks.
  • You can distribute Cron Jobs to multiple computers on a network. Therefore, executing scheduled tasks does not happen if the computer runs Cron crashes. Moreover, the missed jobs will also run manually.

Thus, these limitations make Cron and excellent solution for simple tasks running at a specific time with regular intervals of at least 60 seconds.

Cron Table File

Crontab (Cron Table) is a file format that defines the frequency of Cron tasks. It includes the documents classifying as:

  • System wide Crontab files
  • Individual user Crontab Files

The Crontab documents for customers are defined after their name, and their destination varies according to their OS. The documents are saved in the /var/spool/cron folder in Red Cap allocations. It includes CentOS. The documents are further processed in the /var/spool/cron/crontabs database Unix and Debian.

Although you sequentially modify the customer crontab documents, you should use the crontab prompt. The /etc/crontab document and the plugins in the /etc/cron.d folder are platform crontab documents that only you, as a software developer, can process.

You can also place codes in the /etc.cron. These files will implement monthly/weekly./daily/hourly.

Install Cron

By default, the Cron package comes pre installed on all Linux operating systems. However, if the Cron package is not installed, you can install it on Ubuntu and Debian operating system using the following command:

				
					apt install cron
				
			

After installing the Cron package, start the Cron service and enable it to start at system reboot:

				
					systemctl start cron
systemctl enable cron
				
			

Crontab Basic Syntax

Before scheduling tasks using the Crontab, you will need to understand the basic syntax and format of Crontab.

A brief explanation of each field is shown below:

  • Minute: It will run in range from 0 to 59.
  • Hour: It will run in a range from 0 to 23 in 24 hours format.
  • Day of the month: It will run in a date range from 1 to 31.
  • Month: It will run in a month range from 1 to 12.
  • Day of the week: It will run from Sunday to Saturday.

Crontab also uses some special syntax that allows you to schedule cron jobs at time intervals without worry about notation. Here are the list:

  • @hourly will run cron jobs once an hour.
  • @daily will run cron jobs every day.
  • @weekly will run cron jobs once a week.
  • @monthly will run cron jobs on the first day of every month.
  • @yearly will run cron jobs once a year on 1st January.
  • @reboot will run cron jobs at system reboot.

How to Setup Cron Jobs

To setup a cron job, you will need to edit the Crontab configuration file. Run the following command to edit the Crontab configuration file for the current user:

				
					crontab –e
				
			

You should see the following configuration file:

Here, you can add Cron jobs one per line. Save and close the file when you are done. If you want to create Cron jobs for different users, use the following syntax:

				
					crontab –u username –e
				
			

You can run the following command to see a list of all scheduled cron jobs:

				
					crontab -l
				
			

To see the Cron jobs for different users, run the following command:

				
					crontab -u username -l
				
			

To remove all scheduled Cron jobs, run the following command:

				
					crontab -r
				
			

Important Cron Jobs Examples

In this section, we will show you some important Cron job examples that will help you perform your day to day jobs.

Use the following Cron jobs to run backup.sh script every minute:

				
					* * * * * /root/backup.sh
				
			

The following jobs will run the backup script after every 5 minutes.

				
					*/5 * * * *  /root/backup.sh
				
			

You can use the following Cron jobs to run the backup script at every Tuesday at 6 AM.

				
					0 6 * * tue  /root/backup.sh
				
			

The following jobs will run the backup script at a specific month:

				
					* * * jan,may,aug *  /root/backup.sh
				
			

Use the following Cron jobs to run a backup script every 3 seconds:

				
					* * * * * /root/backup.sh
* * * * *  sleep 3; /root/backup.sh
				
			

To run the backup script every Tuesday, Wednesday, and Thursday at 4:00 AM:

				
					0 4 * * 2-4 /root/backup.sh 
				
			

Use the following syntax to run a backup script at midnight every Wednesday between the 1st and 15th of every month.

				
					0 0 1,15 * 3 /root/backup.sh 
				
			

You can use the following syntax to run the backup script every day from Monday to Friday every hour from 8 to 5 pm.

				
					00 08-17 * * 1-5 /root/backup.sh 	
				
			

Use the following jobs to create a backup every hour.

				
					0 * * * * /root/backup.sh	
				
			

How to Automate MySQL Database Backup Using Cron Jobs

In this section, we will create a simple shell script for MySQL database backup and automate it using Cron Jobs.

Create a MySQL Backup Script

Open your command line interface and create a MySQL backup script using the nano command:

				
					nano /opt/mysql-backup.sh
				
			

Add the following contents:

				
					#!/bin/bash

export PATH=/bin:/usr/bin:/usr/local/bin
TODAY=`date +"%d%b%Y"`

################################################################
################## Update below values  ########################

DB_BACKUP_PATH='/mnt/dbbackup'
MYSQL_HOST='localhost'
MYSQL_PORT='3306'
MYSQL_USER='root'
MYSQL_PASSWORD='your-mysql-root-password'
DATABASE_NAME='mysqldb'
BACKUP_RETAIN_DAYS=30   ## Number of days to keep local backup copy

#################################################################

mkdir -p ${DB_BACKUP_PATH}/${TODAY}
echo "Backup started for database - ${DATABASE_NAME}"


mysqldump -h ${MYSQL_HOST} \
		  -P ${MYSQL_PORT} \
		  -u ${MYSQL_USER} \
		  -p${MYSQL_PASSWORD} \
		  ${DATABASE_NAME} | gzip > ${DB_BACKUP_PATH}/${TODAY}/${DATABASE_NAME}-${TODAY}.sql.gz

if [ $? -eq 0 ]; then
  echo "Database backup successfully completed"
else
  echo "Error found during backup"
fi


##### Remove backups older than {BACKUP_RETAIN_DAYS} days  #####

DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`

if [ ! -z ${DB_BACKUP_PATH} ]; then
      cd ${DB_BACKUP_PATH}
      if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
            rm -rf ${DBDELDATE}
      fi
fi

				
			

Save and close the file then set the executable permission to run it properly:

				
					chmod +x /opt/mysql-backup.sh
				
			

Schedule Backup Script Using Crontab

Next, you will need to create a Cron Jobs to schedule the script that run on a daily basis and complete MySQL database backup.

Run the following command to create a new Cron jobs:

				
					crontab -e
				
			

Add the following configuration to run backup script daily at 6:00 AM.

				
					0 6 * * * root /opt/mysql-backup.sh
				
			

Save and close the file when you are finished.

Thank you for reading How to Setup Cron Jobs in Linux to Schedule Tasks (Automation). We shall conclude.

How to Setup Cron Jobs in Linux to Schedule Tasks (Automation) Conclusion

In this guide, we introduced Cron Jobs with its syntax. We also showed you how to use Cron Jobs with different examples. Use Cron Jobs in the production environment to automate your important tasks.

Cron jobs are an excellent way for system administrators and web developers to manage repetitive tasks. All that needs to be done is to enter the proper commands and choose the correct execution time.

Take a look at more of our content about Ubuntu over here

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x