A method of using Cron to perform tasks regularly under Linux _linux

Source: Internet
Author: User
Tags cron script
Name: crontab

Use Rights: All users

How to use:

crontab file [-u user]-replaces the current crontab with the specified files.

Crontab-[-u user]-replaces the current crontab with standard input.

crontab-1[user]-lists the user's current crontab.

crontab-e[user]-Edit user's current crontab.

crontab-d[user]-deletes the user's current crontab.

Crontab-c dir-Specifies the directory for crontab.

crontab file format: M H d M D cmd.

Basic format:

* * * * command

Time-sharing and Lunar Week command

M: Minutes (0-59). Per minute with * or */1

H: Hours (0-23). (0 indicates 0 points)

D: Days (1-31).

M: Month (1-12).

D: Days of the week (0~6,0 for Sunday).

CMD to run the program, the program was sent to SH execution, this shell only user,home,shell these three environment variables

Description

Crontab is used to allow the user to execute a program at a fixed time or at a fixed interval, in other words, a user-like schedule. -u user is the time table that specifies the user, as long as you have permission (for example, root) to specify the schedule for others. If you do not use-u user, it means setting your own schedule.

Parameters:

CRONTAB-E: Execute the text editor to set the time table, the default text editor is VI, if you want to use another text editor, please set the VISUAL environment variables to specify the use of the text editor (for example, Setenv VISUAL Joe)

Crontab-r: Deletes the current schedule table

Crontab-l: List the current schedule

crontab file [-u user]-replaces the current crontab with the specified files.

The format of the schedule table is as follows:

F1 F2 F3 f4 f5 program

Where F1 is the minute, F2 represents the Hour, F3 represents the day of the month, the F4 represents the month, and the F5 represents the day of the one week. Program represents the programs to be executed.

When F1 is *, it means that the PROGRAM,F2 is executed every minute for *, and the rest of the program is executed every hour.

When F1 is a-b to be executed from the time of the first a minute to the B minute, the F2 is a-b to be performed from A to a B-hour, and the remainder of the analogy

When F1 is */n, it is executed once every n minutes, F2 is performed once per N-hour intervals for */n, and the rest

When F1 is a, B, C,... The first A, B, C,... Minutes to execute, F2 for a, B, C,... The first is a, B, c ... An hour to execute, and the rest of the analogy

The user can also store all the settings in the file file, using crontab file to set the schedule.

Example:

#每天早上7点执行一次/bin/ls:

0 7 * * */BIN/LS

In December, every day at 6 to 12, every 3 hours of the morning/usr/bin/backup are performed:

0 6-12/3 */usr/bin/backup

Send a letter to Alex@domain.name from Monday to Friday every 5:00:

0 * * 1-5 mail-s "HI" Alex@domain.name </tmp/maildata

Every month at midnight 0:20, 2:20, 4:20 .... Execute echo "haha"

0-23/2 * * * echo "haha"

Attention:

When the program is executed at the time you specify, the system will send you a letter showing the execution of the program, if you do not wish to receive such a letter, please add >/dev/null 2>&1 after each line blank

Example 2:

#每天早上6点10分

6 * * * Date

#每两个小时

0 */2 * * * Date

#晚上11点到早上8点之间每两个小时, 8 in the morning.

0 23-7/2,8 * * * Date

#每个月的4号和每个礼拜的礼拜一到礼拜三的早上11点

0 4 * mon-wed date

#1月份日早上4点

0 4 1, * date

Example

$crontab-L lists the user's current crontab.

/usr/lib/cron/cron.allow says who can use the crontab command. If it is an empty file, it indicates that no user can schedule a job. If the file does not exist and there is another file/usr/lib/cron/cron.deny, only users who are not included in this file can use the crontab command. If it is an empty file, it indicates that any user can schedule a job. Two files exist at the same time Cron.allow first, if none exists, only super users can schedule jobs.

Some examples of crontab files:

* * * */usr/local/etc/rc.d/lighttpd restart

The above example represents 21:30 restart Apache per night.

4 1,10,22 * */USR/LOCAL/ETC/RC.D/LIGHTTPD restart

The above example represents the 4:45 reboot of Apache for 1, 10, and 22nd per month.

1 * * 6,0/USR/LOCAL/ETC/RC.D/LIGHTTPD restart

The above example shows the 1:10 reboot of Apache every Saturday and Sunday.

0,30 18-23 * * * */usr/local/etc/rc.d/lighttpd restart

The example above shows that Apache is restarted every 30 minutes from 18:00 to 23:00 every day.

0 * * 6/USR/LOCAL/ETC/RC.D/LIGHTTPD restart

The above example indicates that 11:00 PM restarts Apache every Saturday.

* */1 * * * */usr/local/etc/rc.d/lighttpd restart

Restart Apache every hour

* 23-7/1 * * * */usr/local/etc/rc.d/lighttpd restart

From 11 o'clock to 7 in the morning, restart Apache every hour.

0 4 * mon-wed/usr/local/etc/rc.d/lighttpd restart

4th per month with 11 points per Monday to Wednesday restart Apache

0 4 1/USR/LOCAL/ETC/RC.D/LIGHTTPD * Restart

Restart Apache at 4 o ' January 1.

Example:

Separated by commas in the middle of each two time value.

In addition to the numbers there are a few special symbols is "*", "/" and "-", ",", * represents all the values in the range of numbers, "/" for each meaning, "*/5″ said every 5 units,"-"representing from a number to a number,", "separate several discrete numbers.

Every morning at 6.

0 6 * * * echo "Good morning." >>/tmp/test.txt//Note that pure echo does not see any output from the screen because cron emails any output to Root's mailbox.

Every two hours

0 */2 * * echo "Have a break now." >>/tmp/test.txt

Between 11 o'clock and 8 in the morning, every two hours, eight in the morning.

0 23-7/2,8 * * * echo "Have a Good Dream:)" >>/tmp/test.txt

4th a month and a week on Monday to three in the morning 11.

0 4 * 1-3 command line

January 1 morning, 4.

0 4 1 1 * command line

After each edit of a user's cron settings, Cron automatically generates a file with the same name as this user under/var/spool/cron, and the user's cron information is recorded in this file, which is not directly editable and can only be edited with CRONTAB-E. After Cron starts, read the file every time it is written, and check if you want to execute the commands inside. Therefore, you do not need to restart the Cron service after this file has been modified.

2. Edit/etc/crontab File Configuration cron

The cron service does not only have to read all the files in the/var/spool/cron every minute, but also read the/etc/crontab, so we can configure the file to do something with the cron service. The crontab configuration is for a user, and editing/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 there is an error, or if there is data output, the data is sent to this account as mail

home=///user Run path, this is the root directory

# Run-parts

* * * * * root run-parts/etc/cron.hourly//hourly execution of scripts within/etc/cron.hourly

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

4 * * 0 root run-parts/etc/cron.weekly//per week execute/etc/cron.weekly script

4 1 * * Root run-parts/etc/cron.monthly//monthly to execute/etc/cron.monthly script

Second, cron timing

Cron is a regular execution tool under Linux that can run jobs without human intervention. Because Cron is a built-in service for Linux, it does not automatically get up and you can start and close this service in the following ways:

/sbin/service crond Start//boot service

/sbin/service Crond Stop//Off service

/sbin/service crond Restart//Restart service

/sbin/service Crond Reload//Reload Configuration

You can also start this service automatically when the system is started:

At the end of the/etc/rc.d/rc.local script, add:

/sbin/service Crond Start

Now that the Cron service is in the process, we can use this service, and the Cron service provides the following interfaces for everyone to use:

1. Edit directly with 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 required by the general root user when executing this command

CRONTAB-L//list details of a user's cron service

Crontab-r//Delete a user's cron service

CRONTAB-E//Edit a user's cron service

For example, root 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 a cron service, there are some formatting and conventions for editing the content, input: Crontab-u root-e

into the vi editing mode, the contents of the edit must conform to the following format: */1 * * * * ls >>/tmp/ls.txt

The first part of this format is the set of time, the next part is the command to execute, if there are too many commands to execute, you can write these commands into a script, and then call the script here directly, and then remember to write the full path of the command. Time set we have a certain agreement, the front five * number represents five digits, the number of the value range and the meaning is as follows:

Minutes (0-59)

Hours (0-23)

Date (1-31)

Month (1-12)

Week (0-6)//0 on behalf of Sunday

In addition to the numbers there are a few special symbols is "*", "/" and "-", ",", * represents all the values in the range of numbers, "/" for each meaning, "*/5" means every 5 units, "-" representing from a number to a number, "," separate several discrete numbers



Cron usage is simple: start with a crash:
First step: Write cron script files. For example: Name a crontest.cron text file, just write one line:
15,30,45,59 * * * * echo "xgmtest ..." >> xgmtest.txt
Indicates that every 15 minutes, the Print command is executed once
Step Two: Add timed tasks. Executes the command "Crontab Crontest.cron". Get
Step three: If you are not assured, you can enter "Crontab-l" to see if there are scheduled tasks
Detailed information:

Crontab usage
The crontab command is used to install, delete, or list tables used to drive cron background processes. In other words, the user places the sequence of commands to be executed in the crontab file for execution. Each user can have his or her own crontab file. Let's take a look at how to create a crontab file.

crontab files under/var/spool/cron cannot be directly created or modified directly. The crontab file is obtained by the crontab command. Now assume that you have a user name of foxy and you need to create one of your own crontab files. You can start by using any text editor to create a new file, and then write the command you want to run and the time that you want to execute regularly.

Then save the disk and exit. Suppose the file is/tmp/test.cron. After that, use the crontab command to install the file, making it the user's crontab file. Type:

Crontab Test.cron

Such a crontab file is set up. You can go to the/var/spool/cron directory to view, found a more than one foxy file. This file is the required crontab file. View the contents of the file with the more command to find that there are three lines of information in the header:

#DO not EDIT This file-edit the master and reinstall.

# (Test.cron installed on Mon Feb 22 14:20:20 1999)

# (Cron version--$Id: crontab.c,v 2.13 1994/01/17 03:20:37 vivie Exp $)

Probably means:

#切勿编辑此文件-Edit your source file and reinstall it if you need to change it.

#test. cron File installation time: 14:20:20 02/22/1999

If you need to change the contents of the command, you will need to edit the original file again, and then use the crontab command to install it.

Users who can use the crontab command are limited. If/etc/ Cron.allow file exists, only the users listed in it can use the command, and if the file does not exist but the Cron.deny file exists, only users not listed in the file will be able to use the crontab command; If two files do not exist, it depends on the settings of some parameters, which may be only allowed for Superuser This command, or it may be available to all users.

The syntax format for the crontab command is as follows:

crontab [-u user] File

crontab [-U User]{-l-r-e}

The first format is used to install a new crontab file, install the file referred to in the Chun-ile, and if the "-" symbol is used as the filename, that means using standard input as the source of the installation.

-U If you use this option, you specify which specific user's crontab file will be modified. If you do not specify this option, Crontab will default to the operator's own crontab, that is, the crontab file of the user executing the crontab command will be modified. Note, however, that if you use the SU command to use the crontab command again, there is a good chance of confusion. So if you're using the SU command, it's best to use the-u option to specify which user's crontab file.

-L Displays the current crontab on the standard output.

-R Deletes the current crontab file.

-e Edits the current crontab file using the editor that the visual or editor environment variable refers to. When an end edit is left, the edited file is automatically installed.

[Example 7]

# crontab-l #列出用户目前的crontab.

6 * * * Date

0/2 * * Date

0 23-7/2,8 * * * Date

#

How to enter the command and time that you want to execute in the crontab file. Each row in the file includes six fields, the first five of which are the time when the command was executed, and the last field is the command to be executed. Each field is delimited by a space or tab. The format is as follows:

Minute hour day-of-month month-of-year day-of-week commands

The first is the minute, the second is the hour, the third is the day of the one months, the fourth is the month ordinal of the year, the fifth is the week of the week, and the sixth is the order to be executed. None of these items can be empty and must be filled in. If the user does not need to specify several of these items, then you can use the * instead. Because * is a wildcard character, it can be substituted for any characters, so it can be considered any time, that is, the item is ignored. The legal scope of each item is given in table 4-1.

Table 4-1 The legal scope of the specified time

Time Minute hour Day-of-month month-of-year Day-of-week
Legal value 00-59 00-23 01-31 01-12 0-6 (0 is Sunday)

This allows the user to write an unlimited number of lines to the crontab file to complete an unlimited number of commands. Command fields can be written to all commands and symbols that can be written on the command line, and all other time domains support enumeration, which means that many time values can be written to the domain, and a comma is used to separate each of the two time values, as long as any one of those time values executes the command.

In addition to the numbers there are several special symbols is "*", "/" and "-", ",", * represents all the values in the range of numbers, "/" for each Meaning, "/5" means every 5 units, "-" represents from a number to a number, "," separate several discrete numbers.

Several examples:

Every morning at 6.
0 6 * * * echo "Good morning." >>/tmp/test.txt//Note that pure echo does not see any output from the screen because cron emails any output to Root's mailbox. Every two hours
0 */2 * * * echo "Have a break now." >>/tmp/test.txt Night 11 o'clock to 8 a.m. every two hours, morning eight.
0 23-7/2,8 * * echo "Have a Good Dream:)" >>/tmp/test.txt 4th per month and 11 in the morning of Monday to Thursday three
0 4 * 1-3 command line1 month 1st morning 4
0 4 1 1 * command line Shell=/bin/bash path=/sbin:/bin:/usr/sbin:/usr/bin mailto=root//If there is an error, or if there is a data output, the data is sent to this account as a message home= ///user Run path, this is the root directory # run-parts * * * * * root run-parts/etc/cron.hourly//Hourly Execution/etc/cron.hourly Script 4 * * * Oot run-parts/etc/cron.daily//daily execution of scripts within/etc/cron.daily 4 * * 0 root run-parts/etc/cron.weekly//per week/etc/cron.weekly Within the Script 4 1 * * Root run-parts/etc/cron.monthly//monthly to execute/etc/cron.monthly within the script everyone notice the "run-parts" This parameter, if you remove this parameter, You can then write a script name that you want to run instead of a folder name.
This means that any day any month, in fact, every day 4 o'clock in the afternoon, 5, 6 points 5 min, min, min, min, Min, and Min, the implementation of the command.
5,15,25,35,45,55 16,17,18 * * command in every Monday, three, five 3:00 system into the maintenance state, reboot the system. The following fields should be written in the crontab file:
* * 1,3,5 shutdown-r +5 then save the file as a foxy.cron, and then type crontab foxy.cron install the file.
10 minutes per hour, 40 minutes to execute the Innd/bbslin command in the user directory:
10,40 * * * * * * Innd/bbslink 1 minutes per hour to execute the Bin/account in the user directory:
1 * * * * * * * * Bin/account daily 3:20 A.M. Execute the following two instructions (each instruction, separated) as shown below in the user directory:
3 * * * (/bin/rm-f expire.ls logins.bad;bin/expire$#@62;expire.1st)
Each year in January and April, 4th to 9th, 3:12 and 3:55, execute/bin/rm-f expire.1st This instruction and add the results after mm.txt this file (mm.txt file is located in the user's own directory location).
12,55 3 4-9 1,4 */bin/rm-f expire.1st$#@62;$#@62;mm.txt

The correct use of crontab (short save everyone Time) command: 1 man cron 2 man crontab 3 man 5  There's a 5 in the middle of crontab ==> . Command "CRONTAB&NBSP;-E": --------------------------------------------------------------------------------  PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin  #这是盲点, did not want to set, again and again disappointment. [Colon-delimited] display=:0.0  #加上吧 with a colon with a period.  #  minutes   clock   day   month   Week   command  1 23 1 8 * shutdown -h  +3  #1月8日23点1分关机 (3 minutes delay)  1,4,7 23 1 8 * # 1 minutes, 4 minutes, 7 minutes [January 8 23 O'Clock] * /3 23 1 8 * # 0,3,6,9. Every 3 minutes (or every 3 minutes, a little different from every 3 minutes)  [1-10]/3 23 1  8 * # 1 points, 4 points, 7 points [from 1, plus 3 minutes, until greater than 10==> this is the correct solution to the  ] @reboot shutdown -k  now  #这行能把你吓坏, turn off the machine on a boot (if "K" replaced "-H").   "@reboot" indicates execution at startup.  ---------------------------------End--------------------------------------------  Another script:  ****** ******************* [0-59]/5 23 * * *  shutdown -h now  #每天晚上11点每隔5分钟关一次机, the wish is very good, but will not execute, because no path variable, the solution see the downward.  [0-59]/5 23 * * * /sbin/shutdown -h now  #保证关得很死, given the path.  0 6 1 8 * xmms /music/zhangchu/thrashed .mp3  #明天早上6点钟放首歌叫我. But sleep until 7 o'clock still didn't hear music, sad and disappointed. [display=:0.0]. The last point to add to the bank: Today 99% motherboards are supported on a regular boot, no alarm clock can call the computer to wake you, the option in the BIOS power supply [wake up by alarm].  *********************************END*******************************************  can be freely modified, Originally posted on the Linuxsir website.  
Let's look at a super user's crontab file:
#Run the ' Atrun ' program every minutes #This runs anything that ' s due to Run from ' at '.   ' at ' or ' atrun '. 0,5,10,15,20,25,30,35,40,45,50,55 * * * * * */usr/lib/atrun 7 * * * * * updatedb 8,10,22,30,39,46,54,58 * * * * */bin/sync

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.