Ugacomp

What are Cron Jobs and how to use them in Linux Systems?

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM

CLOUD VPS M

$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM

CLOUD VPS L

$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

Cron is a time-based job scheduler in Unix-like operating systems. It allows users to schedule jobs, which are typically commands or scripts; to run periodically at fixed times, dates, or intervals. Cronjobs are particularly useful for automating repetitive tasks, such as backups, system maintenance, and other routine activities.

Displaying the Cron Table

To display the cron jobs for a user in Linux, you can use the crontab command with the -l option. Open a terminal and run the following command:

crontab -l

This command lists the current user’s cron jobs. If the user does not have any scheduled cron jobs, it will return an empty output.

If you run the crontab -l command, the output will show the current user’s scheduled cron jobs. Here’s an example of what the output might look like:

# m  h  dom mon dow   command
  0  2  *   *   *     /path/to/backup-script.sh
  15 3  *   *   1-5   /usr/bin/apt-get update >> /var/log/update.log
  0  0  *   *   *     /usr/sbin/logrotate /etc/logrotate.conf

Let’s break down the columns in the output:

  • The first column represents minutes (0-59).
  • The second column represents hours (0-23).
  • The third column represents the day of the month (1-31).
  • The fourth column represents the month (1-12).
  • The fifth column represents the day of the week (0-6, where 0 is Sunday).
  • The sixth column represents the command or script to be executed.

In this example:

  1. The first line schedules a backup script to run every day at 2:00 AM.
  2. The second line updates the package lists every weekday (Monday to Friday) at 3:15 AM.
  3. The third line runs the log rotation every day at midnight.

This is just a hypothetical example; the actual cron jobs on your system will depend on your specific configuration and requirements.

view cron jobs for specific users

If you want to view the cron jobs for a specific user, you can use:

crontab -u username -l

Replace username with the actual username of the user whose cron jobs you want to display.

View system-wide cron jobs

To view the system-wide cron jobs (root user’s cron jobs), you can use:

sudo crontab -l

This will display the cron jobs scheduled for the root user.

Remember that these commands only display the user-specific cron jobs. System-wide cron jobs or jobs scheduled by other users will not be shown unless you have the necessary permissions to view them.

Editing the Cron Table

To edit your cron jobs, you can use the crontab -e command, which opens the user’s crontab file in the default text editor.

crontab -e

If it’s your first time editing the cron jobs, you might be prompted to choose a text editor. You can select your preferred editor (such as nano, vim, or emacs). If you’re not familiar with any specific editor, you can choose nano, which tends to be more user-friendly for beginners.

When you run crontab -e, it opens the user’s crontab file in the default text editor. The content of this file might be empty if the user doesn’t have any existing cron jobs. If there are existing cron jobs, you will see them in the text editor.

Here’s a hypothetical example of what the crontab -e output might look like:

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task.
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').

# m  h  dom mon dow   command
0  2  *   *   *     /path/to/backup-script.sh
15 3  *   *   1-5   /usr/bin/apt-get update >> /var/log/update.log
0  0  *   *   *     /usr/sbin/logrotate /etc/logrotate.conf

This example shows three scheduled cron jobs:

  1. A backup script that runs every day at 2:00 AM.
  2. An update of package lists every weekday (Monday to Friday) at 3:15 AM.
  3. Log rotation every day at midnight.

The lines starting with # are comments and are not executed. Each uncommented line represents a scheduled task with its respective timing and command.

Adding new cron jobs

The syntax for adding cron jobs using the crontab -e command involves specifying the schedule (timing) and the command to be executed. The general syntax is as follows:

m h dom mon dow command

Here’s a breakdown of the fields:

  • m: Minute (0 – 59)
  • h: Hour (0 – 23)
  • dom: Day of the month (1 – 31)
  • mon: Month (1 – 12)
  • dow: Day of the week (0 – 6, where 0 is Sunday)
  • command: The command or script to be executed

You can use the following symbols in the fields:

  • *: Wildcard (matches any value)
  • ,: List separator (e.g., 1,15 means the 1st and 15th)
  • -: Range separator (e.g., 1-5 means 1 to 5)
  • /: Step value (e.g., */15 means every 15)

Cron Jobs Use Case Scenarios & applications

Systems administrators use cron tasks to automate how applications or scripts interact or behave in the Linux environment. Let’s break down some of them;

Scheduling a Simple Command

The basic syntax for scheduling a command to run at a specific time is as follows:

* * * * * command_to_be_executed

Each asterisk represents a unit of time (minutes, hours, days, months, days of the week), and you can replace them with specific values or ranges.

Run a script every day at a specified time

To run a script every day at a specified time using cron jobs, you need to set up a cron expression in the crontab file. The basic syntax for scheduling a cron job is as follows:

m h dom mon dow command

Here’s an example to run a script every day at 3:30 AM:

30 3 * * * /path/to/your/script.sh
  • 30: Minutes (30th minute)
  • 3: Hours (3 AM)
  • *: Any day of the month
  • *: Any month
  • *: Any day of the week

Replace /path/to/your/script.sh with the actual path to your script. This cron expression will execute the script every day at 3:30 AM.

To add this to your crontab, open your crontab file for editing using the command:

   crontab -e

Add the line with the cron expression:

   30 3 * * * /path/to/your/script.sh

Save the changes and exit the editor.

This cron job will now run your script every day at the specified time. Make sure that your script is executable (chmod +x /path/to/your/script.sh) and that the cron job has the necessary permissions to execute the script.

Run a Script or command every Weekday at a specified time

To run a script or command every weekday (Monday to Friday) at a specified time using cron jobs, you can set up a cron expression that includes the specific days of the week. The cron expression format is as follows:

m h dom mon dow command

Here’s an example to run a script every weekday at 8:00 AM:

0 8 * * 1-5 /path/to/your/script.sh
  • 0: Minutes (0th minute)
  • 8: Hours (8 AM)
  • *: Any day of the month
  • *: Any month
  • 1-5: Monday to Friday (1 = Monday, 5 = Friday)
  • /path/to/your/script.sh: Replace with the actual path to your script

To add this to your crontab:

Open your crontab file for editing using the command:

   crontab -e

Add the line with the cron expression:

   0 8 * * 1-5 /path/to/your/script.sh

Save the changes and exit the editor.

This cron job will now run your script every weekday at 8:00 AM. Make sure that your script is executable (chmod +x /path/to/your/script.sh) and that the cron job has the necessary permissions to execute the script.

Run a backup script on a specified day and time

You can use the cron tasks to automate the backup process on your Linux system

0 0 * * 0 /path/to/backup-script.sh

For example, using rsync with cron jobs is a common practice for automating file synchronization between directories, either locally or over a network. Here’s a basic example of how you can set up a cron job to run an rsync command:

Use the following syntax to specify the schedule and the rsync command:

m h dom mon dow rsync options source destination
  • m: Minute (0 – 59)
  • h: Hour (0 – 23)
  • dom: Day of the month (1 – 31)
  • mon: Month (1 – 12)
  • dow: Day of the week (0 – 6, where 0 is Sunday)
  • rsync: The rsync command
  • options: Additional rsync options
  • source: Source directory or file
  • destination: Destination directory or file.

Example cron job for syncing a local directory to a remote server every day at 3:00 AM:

 0 3 * * * rsync -avz /local/source/ user@remote:/remote/destination/

In this example:

  • -avz: a for archive mode, v for verbose, and z for compressing files during transfer.
  • /local/source/: Source directory on the local machine.
  • user@remote:/remote/destination/: Destination directory on the remote machine.

Remember to replace the placeholders (/local/source/, user@remote:/remote/destination/) with your actual source and destination paths. Additionally, ensure that you have proper SSH access if you are connecting to a remote server.

Run a command after a certain number of minutes

To run commands at specific intervals, you can use cron jobs by specifying the desired minute intervals in the cron syntax. Here are a few examples:

  • Run a command every 15 minutes

To run a cron job task every 15 minutes, here is the command

*/15 * * * * command_to_be_executed
  • Run a command every 30 minutes

To run a cron job task every 30 minutes, here is the command

*/30 * * * * command_to_be_executed
  • Run a command every 5 minutes

To run a cron job task every 5 minutes, here is the command

*/5 * * * * command_to_be_executed
  • Run a command every 10 minutes

To run a cron job task every 10 minutes, here is the command

*/10 * * * * command_to_be_executed
  • Run a command every 60 minutes (hourly)

To run a cron job task every 60 minutes, here is the command

0 * * * * command_to_be_executed

Example Explanation:

  • */15: This means “every 15 minutes.”
  • */30: This means “every 30 minutes.”
  • */5: This means “every 5 minutes.”
  • */10: This means “every 10 minutes.”
  • 0: This represents the exact minute when the command should run, and * in other fields means “any.”

Make sure to replace command_to_be_executed with the actual command or script you want to run.

It’s important to remember that to schedule these cron jobs, you can use the crontab -e command to edit your user’s crontab file. After adding the desired cron job, save the changes and exit the editor. The specified commands will then run at the specified intervals.

Run a command on a certain date of the month repetitively

To run a cron task on a specific day of the month, you can use the following syntax in your crontab file:

m h dom * * command_to_be_executed

Here, dom represents the day of the month, and you can replace it with the desired day. The fields are as follows:

  • m: Minute (0 – 59)
  • h: Hour (0 – 23)
  • dom: Day of the month (1 – 31)
  • *: Any value for the month and day of the week

For example, to run a command on the 15th day of each month at 3:30 AM, you would use:

30 3 15 * * command_to_be_executed

This means:

  • Minute: 30
  • Hour: 3 (3 AM)
  • Day of the month: 15
  • Any month (*)
  • Any day of the week (*)

Replace command_to_be_executed with the actual command or script you want to run. Save the changes after editing your crontab file using crontab -e.

Updating the Package Lists

You can also automate the process of updating the package list on your Linux system. Here is the sample cron task you can use;

0 4 * * * apt-get update

Using Ranges and Wildcards

In cron expressions, you can use ranges and wildcards to specify time intervals. Here’s how you can use ranges and wildcards in various fields of a cron job:

Ranges in Cron Jobs

In cron jobs, ranges allow you to specify a continuous range of values for a particular time field. A range is defined using a hyphen (-). Ranges are particularly useful for specifying a period during which a cron job should run.

For example, to run a command every day between the 5th and 10th minute of the hour, you would use:

5-10 * * * * command_to_be_executed

Wildcards in Cron Jobs

In cron jobs, wildcards are special characters used to match any valid value within a specific field. The asterisk (*) is the most common wildcard and is used to represent “any” or “every” possible value for that field. For example, to run a command every day at midnight (00:00), you would use:

0 0 * * * command_to_be_executed

Step Values

In the context of cron jobs, step values are used to specify intervals between values in a field. The step value is indicated by the forward slash (/) followed by an integer. It allows you to skip a certain number of units when defining the schedule.

The basic syntax for step values is as follows:

m h dom mon dow command
  • m: Minute (0 – 59)
  • h: Hour (0 – 23)
  • dom: Day of the month (1 – 31)
  • mon: Month (1 – 12)
  • dow: Day of the week (0 – 6, where 0 is Sunday)
  • command: The command or script to be executed

Step values provide a convenient way to create regular and spaced schedules in cron jobs. When using step values, ensure that the resulting schedule aligns with your intended timing and requirements.

Combining Ranges and Wildcards

You can combine ranges and wildcards for more complex schedules. For example, to run a command every day between the 5th and 10th minute of the 3rd hour:

   5-10 3 * * * command_to_be_executed

Or, to run a command every Monday and Wednesday at midnight:

   0 0 * * 1,3 command_to_be_executed

Here, 1,3 represents Monday and Wednesday.

When using wildcards and ranges, ensure that your cron expression accurately reflects your intended schedule. Testing the cron job with a small interval is recommended to confirm that it runs as expected.

Redirecting Output

You can redirect the output of your cronjobs to a file using >> or 2>&1 for both standard output and error.

0 2 * * * /path/to/script.sh >> /path/to/logfile.log 2>&1

These examples illustrate the flexibility and power of cron jobs for automating various tasks on a Linux system. Keep in mind that the paths to commands and scripts may vary based on your system configuration.

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.
 

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.