Linux command to add cron job

How to Automate Tasks with cron Jobs in Linux

Zaira Hira

Zaira Hira

How to Automate Tasks with cron Jobs in Linux

If you’re working in IT, you might need to schedule various repetitive tasks as part of your automation processes.

For example, you could schedule a particular job to periodically execute at specific times of the day. This is helpful for performing daily backups, monthly log archiving, weekly file deletion to create space, and so on.

And if you use Linux as your OS, you’ll use something called a cron job to make this happen.

What is a cron?

Cron is a job scheduling utility present in Unix like systems. The crond daemon enables cron functionality and runs in background. The cron reads the crontab (cron tables) for running predefined scripts.

By using a specific syntax, you can configure a cron job to schedule scripts or other commands to run automatically.

For individual users, the cron service checks the following file: /var/spool/cron/crontabs

Content of /var/spool/cron/crontabs

What are cron jobs in Linux?

Any task that you schedule through crons is called a cron job. Cron jobs help us automate our routine tasks, whether they’re hourly, daily, monthly, or yearly.

Now, let’s see how cron jobs work.

How to Control Access to crons

In order to use cron jobs, an admin needs to allow cron jobs to be added for users in the ‘/etc/cron.allow’ file.

If you get a prompt like this, it means you don’t have permission to use cron.

Cron job addition denied for user John.

To allow John to use crons, include his name in ‘/etc/cron.allow’. This will allow John to create and edit cron jobs.

Allowing John in file cron.allow

Users can also be denied access to cron job access by entering their usernames in the file ‘/etc/cron.d/cron.deny’.

How to Add cron Jobs in Linux

First, to use cron jobs, you’ll need to check the status of the cron service. If cron is not installed, you can easily download it through the package manager. Just use this to check:

# Check cron service on Linux system sudo systemctl status cron.service

Cron job syntax

Crontabs use the following flags for adding and listing cron jobs.

  • crontab -e : edits crontab entries to add, delete, or edit cron jobs.
  • crontab -l : list all the cron jobs for the current user.
  • crontab -u username -l : list another user’s crons.
  • crontab -u username -e : edit another user’s crons.
Читайте также:  Tail on file linux

When you list crons, you’ll see something like this:

# Cron job example * * * * * sh /path/to/script.sh
  • * * * * * represents minute(s) hour(s) day(s) month(s) weekday(s), respectively.
  • sh represents that the script is a bash script and should be run from /bin/bash .
  • /path/to/script.sh specifies the path to script.

Below is the summary of the cron job syntax.

* * * * * sh /path/to/script/script.sh | | | | | | | | | | | Command or Script to Execute | | | | | | | | | | | | | | | | | | | Day of the Week(0-6) | | | | | | | Month of the Year(1-12) | | | | | Day of the Month(1-31) | | | Hour(0-23) | Min(0-59)

Cron job examples

Below are some examples of scheduling cron jobs.

Schedule Scheduled value
5 0 * 8 * At 00:05 in August.
5 4 * * 6 At 04:05 on Saturday.
0 22 * * 1-5 At 22:00 on every day-of-week from Monday through Friday.

It is okay if you are unable to grasp this all at once. You can practice and generate cron schedules with the crontab guru.

How to set up a cron job

In this section, we will look at an example of how to schedule a simple script with a cron job.

Script for printing date.

  1. Create a script called date-script.sh which prints the system date and time and appends it to a file. The script is shown below:

2. Make the script executable by giving it execution rights.

3. Add the script in the crontab using crontab -e .

Here, we have scheduled it to run per minute.

Adding a cron job in crontab every minute.

4. Check the output of the file date-out.txt . According to the script, the system date should be printed to this file every minute.

Output of our cron job.

How to Troubleshoot crons

Crons are really helpful, but they might not always work as intended. Fortunately, there are some effective methods you can use to troubleshoot them.

First, you can try verifying the schedule that’s set for the cron. You can do that with the syntax you saw in the above sections.

2. Check cron logs.

First you need to check if the cron has run at the intended time or not. You can verify this from the cron logs located at var/log/cron . In some distros, logs can be found at /var/log/syslog

Читайте также:  Настройка ip адреса astra linux

If there is an entry in these logs at the correct time, it means the cron has run according to the schedule you set.

Below are the logs of our cron job example. Note the first column which shows the timestamp. The path of the script is also mentioned at the end of the line.

Cron job logs

3. Redirect cron output to a file.

You can redirect a cron’s output to a file and check the file for any possible errors.

# Redirect cron output to a file * * * * * sh /path/to/script.sh &> log_file.log

Wrapping up

Automating tasks, like with cron jobs, reduces the repetitive work you need to do. It also lets machines auto heal and work around the clock without human intervention.

Automation in Linux heavily relies on cron jobs, so you should definitely learn crons and experiment with them.

Thank you for reading until the end. Feedback is always welcome.

If you found this article helpful, do share it with your friends.

Источник

How to Create and Manage Cron Jobs on Linux

Cron is one of Linux’s most useful tools and a developer favorite because it allows you to run automated commands at specific periods, dates, and intervals using both general-purpose and task-specific scripts. Given that description, you can imagine how system admins use it to automate backup tasks, directory cleaning, notifications, etc.

Cron jobs run in the background and constantly check the /etc/crontab file, and the /etc/cron.*/ and /var/spool/cron/ directories. The cron files are not supposed to be edited directly and each user has a unique crontab.

How then are you supposed to create and edit cron jobs? With crontab commands. The crontab is the method you use to create, edit, install, uninstall, and list cron jobs.

The command for creating and editing cron jobs is the same and simple. And what’s even cooler is that you don’t need to restart cron after creating new files or editing existing ones.

Cron Syntax

Just as it is with any language, working with cron is a lot easier when you understand its syntax and there are 2 formats you should know:

A B C D E USERNAME /path/to/command arg1 arg2 OR A B C D E USERNAME /root/backup.sh

Explanation of above cron syntax:

  • A: Minutes range: 0 – 59
  • B: Hours range: 0 – 23
  • C: Days range: 0 – 31
  • D: Months range: 0 – 12
  • E: Days of the week range: 0 – 7. Starting from Monday, 0 or 7 represents Sunday
  • USERNAME: replace this with your username
  • /path/to/command – The name of the script or command you want to schedule
Читайте также:  Cue to wav linux

That’s not all. Cron uses 3 operator symbols which allow you to specify multiple values in a field:

  1. Asterisk (*) : specifies all possible values for a field
  2. The comma (,) : specifies a list of values
  3. Dash (-) : specifies a range of values
  4. Separator (/) : specifies a step value

Now that you know Cron’s syntax and operators, let’s see some cron examples.

Cron Job Examples

The first step to running cron commands is installing your crontab with the command:

Run /root/backup.sh at 3 am every day:

Run script.sh at 4:30 pm on the second of every month:

Run /scripts/phpscript.php at 10 pm during the week:

0 22 * * 1-5 /scripts/phpscript.php

Run perlscript.pl at 23 minutes after midnight, 2am and 4am, everyday:

23 0-23/2 * * * /path/to/perlscript.pl

Run Linux command at 04:05 every Sunday:

5 4 * * sun /path/to/linuxcommand

Cron Options

# crontab -l OR # crontab -u username -l

Delete Cron job for a specific user.

Strings in Crontab

Strings are among the developer’s favorite things because they help to save time by eliminating repetitive writing. Cron has specific strings you can use to create commands quicker:

  1. @hourly : Run once every hour i.e. “0 * * * *
  2. @midnight : Run once every day i.e. “0 0 * * *
  3. @daily : same as midnight
  4. @weekly : Run once every week, i.e. “0 0 * * 0
  5. @monthly : Run once every month i.e. “0 0 1 * *
  6. @annually : Run once every year i.e. “0 0 1 1 *
  7. @yearly : same as @annually
  8. @reboot : Run once at every startup

For example, this is how to backup your system every day:

@daily /path/to/backup/script.sh

At this point, you have all you need to create and manage system tasks using Cron. You can now begin to set up and maintain several environments using scheduled commands.

How much of a Cron user are you? And are there any details you can contribute to the article? The discussion box is below.

When you understand enough about how Crontab works you can use these nifty Crontab generator utilities to generate crontab lines for free.

Also, you can read Ubuntu’s article on how to use Cron here. It has resources that you might find useful.

Источник

Оцените статью
Adblock
detector