Linux timed tasks in-depth learning

Source: Internet
Author: User
Tags cron script crontab syntax

To create a cron service for the current user

1. Type CRONTAB-E edit crontab service file

For example, the contents of the file are:

*/2 * * * */bin/sh/home/admin/jiaoben/buy/deletefile.sh

Save the file and exit

*/2 * * * */bin/sh/home/admin/jiaoben/buy/deletefile.sh

*/2 * * * * This field allows you to set when to execute the script

/bin/sh/home/admin/jiaoben/buy/deletefile.sh This field can set the script you want to execute, note here that bin/sh refers to the path that the script holds after the command that runs the script

2. See if the Crontab service under this user was created successfully with the CRONTAB-L command

3. Start the crontab service

General start-up service with/sbin/service Crond start if the root user's cron service can be crond start with sudo services, it is also important to note that the commands for the different versions of the Linux system-initiated service are different, like my virtual machine only needs sudo service cron Restart can be started if you type service cron start directly under root

4. See if the service is already running with Ps-ax | grep cron

5. Crontab command

The Cron service provides the crontab command to set the Cron service, and here are some of the parameters and instructions for this command:

Crontab-u//Set a user's Cron service, which is usually required by the root user when executing this command
CRONTAB-L//list details of a user cron service
Crontab-r//Delete a cron service with no users
CRONTAB-E//Edit a user's cron service
For example, root to view your cron settings: Crontab-u root-l
Again, for example, Root wants to delete Fred's cron settings: Crontab-u fred-r
When editing the Cron service, the edited content has some formatting and conventions, input: Crontab-u root-e
Enter VI edit mode, the content of the edits must conform to the following format: */1 * * * * ls >>/tmp/ls.txt
Crond resident command for task scheduling
Crond is a command that Linux uses to execute programs on a regular basis. When the operating system is installed, the default is to start the

The Task Dispatch command. The Crond command periodically checks if there is any work to be done,

The work will be performed automatically.

6. crontab Command options:

-u Specifies a user

-l lists a user's task schedule

-R Delete a user's task

-e Edit a user's tasks

7. cron file Syntax:

Hour of the week order

0-59 0-23 1-31 1-12 0-6 Command (value range, 0 for Sunday One a row corresponds to a task)

Remember the meanings of several special symbols:

"*" represents a number in the range of values,
"/" stands for "every",
"-" represents a number to a number,
"," separate a few discrete numbers

8. Writing the Task Scheduler settings file
The CRONTAB-E command can be used to edit, edit the corresponding user's cron file under/var/spool/cron, or modify the/etc/crontab file directly.
The specific format is as follows:
Minute Hour Day Month Dayofweek command
Minutes hours days months days per week order
Each field represents the following meanings:
Minute the first few minutes of every hour to perform the task
Hour the first few hours of the day to perform this task
Day of the month to perform the task
Month months of the year to perform this task
DayOfWeek the day of the week to perform the task
Command Specifies the program to execute
In these fields, other fields are optional except that the Command is a field that must be specified each time.

field, depending on your needs. For a field that is not specified, "*" is used to fill its position.
Examples are as follows:
5 * * * ls Specifies the first 5 minutes of every hour to execute the LS command
5 * * * ls specifies the 5:30 execute LS command per day
7 8 * * ls specifies 7:30 minutes of 8th per month to execute the LS command
5 8 6 * ls specifies that the LS command be executed every June 8 5:30
6 * * 0 ls specifies 6:30 execute ls command per Sunday [Note: 0 for Sunday, 1 for Week 1,

And so on, can also be expressed in English, Sun said Sunday, Mon said Monday and so on. ]

3 10,20 * * ls 3:30 for each month 10th and 20th executes the LS command [note: "," used to connect multiple discontinuous periods]

8-11 * * * ls command is executed at 25 minutes per day at 8-11 Pips [Note: "-" used to connect a continuous period of time]

*/15 * * * * ls is executed every 15 minutes with the LS command [i.e. No. 0 15 30 45 60 minutes per hour to execute the LS command]

6 */10 * ls command is executed every 10 days each month (1, 11, 21, 31st). 6:30 executes the LS command once. ]

Every day 7:50 executes all executables in the/etc/cron.daily directory as root

7 * * * Root run-parts/etc/cron.daily [Note: The Run-parts parameter indicates that all executables in the following directory are executed. ]

9. New Scheduling task

There are two ways to add a dispatch task:
1), at the command line input: CRONTAB-E and then add the corresponding task, Wq save the disk to exit.
2), directly edit the/etc/crontab file, that is, vi/etc/crontab, add the corresponding task.

10. View scheduling Tasks
Crontab-l//List all current Scheduled tasks
Crontab-l-u JP//List all scheduling tasks for user JP

11. Delete Task Scheduling work
Crontab-r//Delete all task scheduling work

12. Steering of task scheduling execution results
Example 1: Execute the LS command 5:30 every day and output the results to the/jp/test file
5 * * * ls >/jp/test 2>&1
Note: 2>&1 indicates execution results and error messages.
Edit/etc/crontab File Configuration cron

Cron service every minute not only to read all the files within/var/spool/cron, but also to read a/etc/crontab, so we configure this file can also use the Cron service to do something. The crontab configuration is for a user, while the edit/etc/crontab is a task for the system. The file format for this file is:

Shell=/bin/bash

Path=/sbin:/bin:/usr/sbin:/usr/bin

Mailto=root//If an error occurs, or if there is data output, the data is sent to this account as an email

home=///user-run path, here is the root directory
# Run-parts

* * * * * root run-parts/etc/cron.hourly//hourly execution

Scripts within the/etc/cron.hourly

4 * * * Root run-parts/etc/cron.daily//daily execution of scripts within/etc/cron.daily

4 * * 0 root run-parts/etc/cron.weekly//weekly execution of scripts within/etc/cron.weekly

4 1 * * Root run-parts/etc/cron.monthly//monthly to execute scripts within/etc/cron.monthly
Attention to the "run-parts" parameter, if you remove this parameter, you can write a script name to run, instead of the folder name

For example:

1) in the command line input: Crontab-e then add the corresponding task, Wq save the disk to exit.

2) Edit the/etc/crontab file directly, i.e. Vi/etc/crontab, add the corresponding task
2 * RM-RF/MNT/FB

*************************************************************************************************************** ************

Use of cron on Ubuntu

Cron is one of the most useful tools in a Linux system, and a cron job is a job that is scheduled to execute when a specified time arrives.
The most common Automated system management and automatic maintenance work, such as a daily notification of a scheduled backup, or a scheduled cleanup of the/tmp/directory. There are also many Web applications that need to perform timed jobs.
This article describes the working mechanism of cron, you can use Cron to implement scheduling job jobs. Cron itself is a daemon, running in the background, with the configuration file "Crontab" to schedule the specified job execution based on time.

First, start the cron service

Basically, all Linux distributions have cron tools preinstalled by default. Even if Cron is not preinstalled, it is simple to execute a command to install it manually:

[email protected]:~# apt-get install cron
    • 1
    • 2

Then check the status of the Cron service, which should run in the background by default. If it does not start, you can start the service manually.

Second, use Cron Help

If cron works correctly, you can use the man command to see the detailed usage of its manual description.

The above command shows how the Crontab manual describes how to use it. If you want to see how to use the information specified by the Cron job, you can:


To exit the display of the Help command manual, press the Q key or the H key.

Iii. use of the crontab command

The following describes how to use the crontab command to implement scheduled scheduling jobs.

1. A list of cron jobs

Use the following command to list the cron jobs scheduled by the current user.

All cron jobs for the current user are listed, and if you want to see other users ' cron jobs, you can use the following command:

2. Edit Cron Jobs

To add a new cron job, or to edit an existing cron job, you can use the following command:

3. Removal of cron jobs

Use the following command to remove the cron job that you have scheduled.

Use the following command to remove all scheduled cron jobs without reconfirmation.

4. Command parameters

-u User: Used to set a user's crontab service;
File:file is the name of the command file, which indicates that file is the Crontab task list and loaded into crontab. If this file is not specified on the command line, the crontab command will accept the commands typed on the standard input (keyboard) and load them into crontab.
-E: Edits the contents of a user's crontab file. If you do not specify a user, the crontab file for the current user is edited.
-L: Displays the contents of a user's crontab file, or displays the contents of the current user's crontab file if no user is specified.
-r: Deletes a user's crontab file from the/var/spool/cron directory and, if no user is specified, deletes the current user's crontab file by default.
-I: Give a confirmation prompt when deleting a user's crontab file.

Iv. Planning tasks with crontab

There are other ways to do this, in addition to using a configuration file to process a scheduled cron job. If you look at the/etc directory, you will find a directory such as Cron.daily, Cron.hourly, cron.monthly, and so on. Therefore, the cron scripts are placed in these directories, and these job scripts are executed at timed intervals based on these directory names.

1. Cron Configuration Type

Cron has two configuration file types that are used to dispatch automation tasks.

1) system level Crontab
These cron jobs are used by system services and critical jobs and require root-level permissions to execute. You can view the system-level cron jobs in the/etc/crontab file.

2) User-level Crontab
A user-level cron job is separate for each user. Each user can therefore create their own cron jobs using the crontab command, and can edit or view their cron jobs using the following commands.


After you select the editor, you can configure the new cron job.

V. Dispatching operations with Crontab

Cron jobs can be dispatched using the specified syntax, and there are shorthand commands that make it easy to manage cron jobs.
The crontab syntax is as follows:

Vi. new Cron Job Configuration instance

Now that you are familiar with the types of CRONTAB commands, syntax, and cron jobs, you can now create some job schedules to test. You can use the Crontab–e command to add.

1. Scheduled jobs that run every minute

The following example creates a cron job that outputs text "test cron job to execute every minute" and sends the text to the [email protected] mailbox every minute.
First edit with crontab command

Write the following script

SHELL=/bin/bashHOME=/MAILTO=”[email protected]”#This is a comment* * * * * echo ‘test cron job to execute every minute‘:wq!    


Once you have saved this cron script file, you can add it to the scheduled job.

2. Scheduling cron job jobs at specified times

If you want to schedule a cron job so that it runs at "7:00 every Thursday," the crontab script should:

Then add it to the dispatch job.

The "00 19" In the above script refers to 7 o'clock in the afternoon, and "4" refers to Thursday.

Vii. Summary

As you can see, it's easy to automate tasks with crontab, and it can perform tasks by minute, hour, week, month, and week. In addition to this, Linux has an at command, which is intended to handle only one-time tasks and requires the ATD service to run first.
Secondly, we should pay attention to the problem of environment variables. Sometimes we create a crontab, but this task cannot be executed automatically, but it is not a problem to perform this task manually, which is usually caused by not configuring environment variables in the crontab file. When you define multiple dispatch tasks in a crontab file, you need to make a special note of the settings of the environment variables, because when we perform a task manually, it is in the current shell environment, the program can certainly find the environment variable, and the system automatically executes the task schedule, it will not load any environment variables, therefore, You need to specify all the environment variables that are required for the task to run in the crontab file, so that the system does not have a problem when it executes the Task Scheduler.
Also pay attention to cleaning up the mail logs of the system users. Each task is scheduled to execute, the system will send the task output information in the form of e-mail to the current system users, so the cumulative, log information will be very large, may affect the normal operation of the system, so it is important to redirect each task.
Finally, note that the newly created cron job will not execute immediately, at least 2 minutes. If you restart the Cron service, it will be executed immediately.

Linux timed tasks in-depth learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.