Connect with us

Website Tutorials

How to Create A Cron Job (2023)

Published

on

How to Create A Cron Job (2023)

System administration, specifically managing your Linux virtual private server (VPS), can be daunting. Performing repetitive tasks requires time, causing admins to look for more efficient ways to do the job.

Fortunately, there are many tools available for automation. One such tool for Linux sysadmins and web developers is the cron job.

Cron jobs allow you to perform basic operations for your VPS hosting. This tutorial covers the basics of creating and scheduling a cron job.

What is a Cron Job?

Cron is a command line utility and job scheduler on Unix-like operating systems (OS). The tasks created in cron, called cron jobs, are scheduled to run periodically at fixed times, dates, or intervals.

Cron jobs are a common automation tactic for data backups and server maintenance tasks. And because cron is a daemon, a program that runs in the background of multitasking operating systems, admins are free to perform other work knowing cron handles scheduled tasks.

Advertisement

Cron jobs are also helpful in downloading internet files and emails at regular intervals. Whether repetitive or one-time tasks, admins schedule cron jobs to simplify basic operations.

How do Cron Jobs Work?

On Unix-like operating systems, cron or any cron jobs work based on the cron file called the crontab file or crontab configuration file. The crontab file is a text file containing the scheduled commands or scripts. The crontab file location is /etc/crontab.

The system or user crontab files are the two types of cron job configuration files used for basic cron job operations. While the sysadmins usually edit the cron files, Unix-like OSs support multiple users. Consequently, users can edit either file depending on their privilege level.

Admins use the system crontab to schedule system-wide tasks. These essential jobs require root privileges.

Sysadmins use the user crontab to schedule user-level tasks. These jobs do not require root access and can be created or edited by most users.

Advertisement

Why use Cron Jobs?

There are a variety of advantages for which admins use cron jobs. No matter the use, cron jobs can help you automate, so you don’t have to worry about them.

Here is a list of several cron job use cases:

  • Running scheduled backups of essential data.
  • Cleaning up temporary files and logs.
  • Sending automated emails or notifications.
  • Running scripts to update your system software.
  • Running jobs to deactivate or delete expired accounts from membership sites.
  • Regularly update database tables.
  • Run jobs to delete cached data periodically.
  • Regular email reporting of broken links in your website content.

One of the most significant advantages of using cron jobs is allowing you to schedule tasks during off-peak hours when server resources are less likely to be in high demand. This feature minimizes user impact and ensures that your server continues running smoothly.

Additionally, by automating tasks with cron jobs, you can reduce the risk of human error and ensure that jobs complete consistently and reliably.

Requirements

  • A server running Linux.
  • Root or sudo privileges for your user account.

Cron Syntax Examples

Cron looks through the configuration files for a list of commands to run. To comprehend the lines in the crontab configuration file, the daemon employs a unique syntax.

To be able to set up a cron job, you must first understand the fundamental pieces that comprise this syntax. A crontab line should take the following format:

* * * * * /directory/command output

Here is a breakdown of the syntax:

Advertisement
  • The asterisks (* * * * *) denote the time, date, and recurrence of the cron job.
  • The /directory/command portion denotes the location and script to run.
  • The output portion is optional and defines how the user is notified upon cron job completion.

Cron Job Time, Date, and Recurrence Formatting

The command’s first five fields are numbers that define when and how frequently it runs. Each position represents a different value and is separated by a space.

The following table outlines the potential values for the fields as well as the example syntax:

FieldPotential ValuesSyntaxDescription
1st * = Minute0 – 593 * * * * The minute is 3, meaning the job is initiated when the system clock shows 3 minutes after the hour.
2nd * = Hour0 – 230 3 * * *The hour is 3, meaning the job runs when the system clock shows 3 am (3 pm is coded as 15).
3rd * = Day0 – 310 0 3 * * The day of the month is 3, meaning the job runs every 3rd day of the month.
4th * = Month0 = none and 12 = December0 0 0 3 *The numerical month is 3, meaning the job runs only in March.
5th * = Day of the Week0 = Sunday and 7 = Sunday0 0 * * 3 3 in this syntax means the job only runs on Wednesdays.

Cron Job Command

The /directory/command portion specifies the executed command. It specifies the precise directory and filename of the script the cron job is to run. While you can specify any command or script you wish, this example points to the root directory and runs a backup.sh script from that location.

/root/backup.sh

Cron Job Output (Optional)

When it runs, Cron automatically emails the crontab file’s owner. While this is a practical method of managing tasks, minor routine tasks can rapidly cause your inbox to get full.

By deactivating the optional output email, you prevent inbox overload. Use cron job special strings to deactivate the output email.

After the time and command fields where output is in the cron syntax, add the string >/dev/null 2>&1 to stop email output. Here is the example syntax with the output section replaced with the appropriate line.

Advertisement
* * * * * directory/command >/dev/null 2>&1

Creating a Cron Job

Step 1: Access the Crontab File

To begin creating a cron job, access the crontab file from the terminal. Using the following command allows you to access the file or create one if it does not already exist.

crontab -e

This command allows users to add, edit, and delete cron jobs using the text editor of their choice.

When accessing the file for the first time, you are prompted to add and confirm an email address to which cron job outputs are sent. Following that screen, you must select the text editor you wish to use.

Step 2: Create the Cron Job

Keeping the backup.sh script from the previous examples, let’s build example cron job commands to enter in the crontab file. The following cron job runs at 2:00 am every first of the month:

* 2 0 * * /root/backup.sh

Here are some additional cron syntax examples:

Advertisement

This command runs the cron job every minute.

* * * * * /root/backup.sh

This command runs the cron job every 30 minutes.

30 * * * * /root/backup.sh

This command runs the cron job every hour.

0 * * * */root/backup.sh

This command runs the cron job every day at midnight.

0 0 * * * /root/backup.sh

This command runs the cron job at 2:00 am every day.

Advertisement
0 2 * * * /root/backup.sh

This command runs the cron job every 1st day of the month.

0 0 1 * * /root/backup.sh

This command runs the cron job every 15th day of the month.

0 0 15 * * /root/backup.sh

This command runs the cron job on December 1st at midnight.

0 0 0 12 * /root/backup.sh

This command runs the cron job on Saturday at midnight.

0 0 * * 6 /root/backup.sh

Best Practices for Cron Job Scheduling

It is important to keep a few best practices in mind when scheduling cron jobs:

Advertisement
  • Avoid overloading the server by not running too many cron jobs simultaneously.
  • Minimize user impact by scheduling cron jobs during off-peak hours.
  • Be clear on what the task does by using descriptive names for your cron jobs.

Step 3: Verify the Cron Job

Once the cron job is created and scheduled, verify it runs correctly by running the following command to check the status. This command specifically lists all currently scheduled cron jobs.

crontab -l

Optional Cron Job Operators

Operators are unique characters that carry out operations on the cron field’s supplied values. Cron syntax also makes use of operators for efficiency.

Here are a few operators to use with your cron commands:

  • Use a forward slash (/) to divide a value into steps. For example, */2 is every other value, */3 is every third value, and */10 is every tenth, etc.
  • Use a hyphen or dash (–) to indicate a range of values.
  • Use a comma (,) to specify separate individual values.
  • Use an asterisk (*) to stand for all values. This operator can keep tasks running every month, or every day of the week.
  • Use the letter L (Last) in the day of the month and day of the week fields to specify the last day of the month or week. For example, 3L in the day of the week field means the last Wednesday of the month.
  • Use the letter W (Weekday) to specify the closest weekday to a given time. For example, when the 1st of the month falls on a Saturday, 1W in the day of the month field runs the command on the following Monday (the 3rd in this example).
  • Use a hash (#) followed by a number from 1 to 5 to specify a specific day of the week. For example, 1#2 means the second Monday of the month.
  • Use a question mark (?) to input no specific value for the day of the month and day of the week fields.

Cron Job Special Strings

Cron job special strings are a part of cron job syntax allowing users to specify the job frequency without inputting the logical sets of numbers. These strings use the at (@) symbol and a descriptor to achieve the same result as the standard syntax.

Here are some of the most common cron job special strings:

  • @yearly or @annually: Runs the command once a year at midnight on January 1st (Standard numerical syntax: 0 0 1 1 *).
  • @monthly: Runs the command once a month at midnight on the first day of the month (Standard numerical syntax: 0 0 1 * *).
  • @weekly: Runs the command once a week at midnight on Sunday (Standard numerical syntax: 0 0 * * 0).
  • @daily or @midnight: Runs the command once a day at midnight (Standard numerical syntax: 0 0 * * *).
  • @hourly: Run the command once an hour at the beginning of the hour (STandard numerical syntax: 0 * * * *).

It is worth noting that not all systems support these strings. The best practice is to confer with the documentation for your VPSs operating system.

Troubleshooting Common Cron Job Issues

Here are some common things to look for if your cron job is not running as it should:

  • Ensure the cron job syntax is correct.
  • Ensure the user has the appropriate permissions to run the command.
  • Ensure the specific cron job does not conflict with other system processes or cron jobs.

Conclusion

Cron jobs are a powerful tool for automating repetitive tasks on your VPS. Following these steps, you can create, schedule, and verify your cron jobs. Remember to follow the best practices when scheduling cron jobs, ensuring they run correctly.

In addition to the basic steps outlined in this tutorial, the additional cron job syntax options provide advanced techniques to create more complex cron jobs. These tools are the building blocks for corn job mastery, helping you make better cron jobs or clean up your existing WordPress jobs.

Advertisement

Stephen Oduntan is the founder and CEO of SirsteveHQ, one of the fastest growing independent web hosts in Nigeria. Stephen has been working online since 2010 and has over a decade experience in Internet Entrepreneurship.

Continue Reading
Advertisement
Comments

Trending

Copyright © 2024 SirsteveHQ. All Rights Reserved.