How to perform tasks with cron at regular intervals under Linux

Source: Internet
Author: User
Tags cron script

Name: Crontab

Usage 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]-Delete the user's current crontab.

Crontab-c dir-Specifies the directory for crontab.

Format of the crontab file: M H d M D cmd.

Basic Format:

* * * * * command

Time-sharing Weekly command

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

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

D: Day (1-31).

M: Month (1-12).

D: Day of the Week (0~6,0 is Sunday).

CMD to run the program, the program is fed into sh execution, this shell only user,home,shell these three environment variables

Description

Crontab is used to allow a user to execute a program at a fixed time or at a fixed interval, in other words, a user-like schedule. -u user refers to the setting of the time table for the specified user, which presupposes that you must have permission (for example, root) to specify another's time schedule. If you do not use the-u user, it means setting your own schedule.

Parameters:

CRONTAB-E: Do a text editor to set the time table, the default text editor is VI, if you want to use a different text editor, you first set the VISUAL environment variables to specify the use of the text editor (for example, setenv visual Joe)

Crontab-r: Delete 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 expressed in minutes, F2 represents hours, F3 represents the day of the month, F4 represents the month, and F5 represents the day of the one week. Program represents the procedure to be executed.

When F1 is * indicates that every minute the program,f2 is executed, the program is executed every hour, and the remainder of the analogy

When the F1 is a-B, it is executed from the time of the minute to the minute of the hour, and the F2 is a-B indicating that it is executed from the first to the first, and the remainder of the analogy

When F1 is */n, it is performed once every n minutes, and F2 is */n for every n-hour interval, with the remainder of the other analogy

When F1 is a, B, C,... A, B, C,... Minutes to execute, F2 for a, B, C,... The time indicated that the first, B, c ... Hours to execute, and the rest of the analogy

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

Example:

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

0 7 * * */BIN/LS

In December, the/usr/bin/backup is performed every 3 hours in the morning from 6 to 12.

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

Monday to Friday every 5:00 send a letter to [email protected]:

0 * * 1-5 mail-s "HI" [email protected] </tmp/maildata

Every day of the month 0:20 midnight, 2:20, 4:20 .... Perform 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 what the program is doing, and if you do not wish to receive such a letter, please add >/dev/null 2>&1 after each line is empty.

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 Jan * Date

Example

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

/usr/lib/cron/cron.allow indicates who can use the crontab command. If it is an empty file indicates that no one user can schedule the job. If the file does not exist and there is another file/usr/lib/cron/cron.deny, only the user who is not included in the file can use the crontab command. If it is an empty file, it indicates that any user can schedule the job. Two files exist at the same time Cron.allow priority, if none exist, only the Superuser can schedule the job.

Some examples of crontab files:

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

The above example shows that 21:30 restarts Apache per night.

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

The above example shows that 4:45 restarts Apache on the 1, 10, and 22nd of the month.

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

The above example shows that 1:10 restarts Apache every Saturday and Sunday.

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

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

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

The above example shows the restart of Apache every Saturday at 11:00am.

* */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-point restart from Monday to Wednesday Apache

0 4 1 Jan */usr/local/etc/rc.d/lighttpd restart

4-point restart of Apache on January 1

Example:

Each of the two time values is separated by commas.

In addition to the numbers there are several special symbols that are "*", "/" and "-", ",", * represent all the values within the range of numbers, "/" for each meaning, "*/5″" represents every 5 units, "-" represents a number to a number, "," separate several discrete numbers.

Every morning at 6.

0 6 * * echo "Good morning." >>/tmp/test.txt//Note simply Echo, no output is visible from the screen, because cron emails any output to root.

Every two hours

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

Every two hours between 11 o'clock and 8 in the morning, eight in the morning.

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

Every month, number 4th and Monday to Sunday, three a.m., 11.

0 4 * 1-3 command line

January 1 morning, 4.

0 4 1 1 * command line

After editing a user's cron settings, Cron automatically generates a file with the same name as the user under/var/spool/cron, and the cron information for this user is recorded in this file, which cannot be edited directly and can only be edited with CRONTAB-E. After Cron starts, read the file once every one of the clocks, and check to see if you want to execute the command inside. Therefore, the Cron service does not need to be restarted after this file has been modified.

2. Edit the/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 of scripts within/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

Second, cron timing

Cron is a timed execution tool under Linux that can run a job without human intervention. Since Cron is a built-in service for Linux, it does not automatically get up, and you can start and shut down this service in the following ways:

/sbin/service Crond Start//Startup service

/sbin/service Crond stop//Shut down service

/sbin/service crond Restart//Restart service

/sbin/service Crond Reload//Reload Configuration

You can also start the service automatically when the system starts:

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

/sbin/service Crond Start

Now cron This service is already in the process, we can use this service, Cron service provides the following kinds of 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 usually required by the root user when executing this command

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

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

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

The first part of this format is the time setting, the next part is the command to execute, if you want to execute too many commands, you can write these commands into a script, and then call this script directly here, you can recall the full path of the command when the call. Time setting we have a certain agreement, the preceding five * number represents five numbers, the value range and meaning of the numbers are 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 several special symbols are "*", "/" and "-", ",", * represents all the values within the range of the number, "/" for each meaning, "*/5" means every 5 units, "-" represents from a number to a number, "," separate several discrete numbers



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

Crontab usage
The crontab command is used to install, delete, or list tables used to drive a cron background process. That is, the user places the sequence of commands that need to be executed in the crontab file for execution. Each user can have their own crontab file. Here's a look at how to create a crontab file.

The crontab file under/var/spool/cron cannot be created directly or modified directly. The crontab file is obtained through the crontab command. Now suppose you have a user named Foxy, and you need to create your own crontab file. You can start by using any text editor to create a new file, and then write to it the command you want to run and the time you want to perform it periodically.

Then save the disk and exit. Assume that 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 and see a more foxy file. This file is the required crontab file. Using the more command to view the contents of the file, you can find that the header has three lines of information:

#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 $)

It probably means:

#切勿编辑此文件-If you need to change, edit the source file and reinstall it.

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

If you need to change the contents of the command, you still need to re-edit the original file, and then use the crontab command to install.

There is a limit to the users who can use the crontab command. If/etc/ Cron.allow file exists, only the user listed in it can use the command, and if the file does not exist but the Cron.deny file exists, only users who are not listed in the file will be able to use the crontab command, and if none of the two files exist, it depends on the settings of some parameters and may be allowed only by Superuser The command can also be used by 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, which installs the files referred to by Ile, and if the "-" symbol is used as the file name, it 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, which means that the crontab file of the user executing the crontab command will be modified. Note, however, that if you use the SU command and then use the crontab command, it is likely that there will be confusion. So if you're using the SU command, it's a good idea 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 Edit the current crontab file using the editor referred to in visual or editor environment variables. When you finish editing, 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 to execute in the crontab file. Each row in the file contains six fields, the first five of which are the time the specified command was executed, and the last field is the command to be executed. Spaces or tabs are used to separate each field. The format is as follows:

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

The first item is the minute, the second is the hour, the third is the day of the one month, the fourth is the first month of the year, the fifth item is the week of the week, and the sixth item is the command to execute. 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 * instead. Because * is a wildcard, can replace any character, so it can be considered any time, that is, the item is ignored. The legal range for each item is given in table 4-1.

Table 4-1 The legal range 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 infinite number of commands. Command fields can be written to all commands and symbols that can be written at the command line, and all other time domains support enumeration, that is, the number of time values that can be written in a domain, as long as any one of these time values executes a command, separated by commas between each of the two time values.

In addition to the numbers there are several special symbols that are "*", "/" and "-", ",", * represent all the values within the range of the number, "/" for each meaning, "/" for each of the 5 units, "-" represents from a number to a number, "," separate several discrete numbers.

A few examples:

Every morning at 6.
0 6 * * echo "Good morning." >>/tmp/test.txt//Note simply Echo, no output is visible from the screen, because cron emails any output to root. Every two hours
0 */2 * * echo "has a break now." >>/tmp/test.txt 11 o'clock to 8 a.m. every two hours, eight a.m.
0 23-7/2,8 * * * echo "a good Dream:)" >>/tmp/test.txt 4th per month and Monday to Friday, three a.m. 11.
0 4 * 1-3 command line1 month 1st morning 4 points
0 4 1 1 * command line Shell=/bin/bash path=/sbin:/bin:/usr/sbin:/usr/bin mailto=root//If an error occurs or 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 Execute script within/etc/cron.hourly 4 * * * r Oot run-parts/etc/cron.daily//Daily Execute script within/etc/cron.daily 4 * * 0 root run-parts/etc/cron.weekly//weekly execution/etc/cron.weekly Within the Script 4 1 * * Root run-parts/etc/cron.monthly//Every month to execute the script inside the/etc/cron.monthly everyone notice "run-parts" This parameter, if you remove this parameter, You can then write a script name to run, not the folder name.
This means that any day any month, in fact, the daily 4 o'clock in the afternoon, 5 points, 6 points of 5 min, min, min, min, min, min, when the execution of orders.
5,15,25,35,45,55 16,17,18 * * * command on every Monday, three, five 3:00 the system enters the maintenance state and restarts the system. Then the following fields should be written in the crontab file:
* 1,3,5 Shutdown-r +5 then save the file as Foxy.cron, and then type crontab foxy.cron to install the file.
10 minutes per hour, 40 minutes execute the innd/bbslin command in the user directory:
10,40 * * * * Innd/bbslink 1 minutes per hour execute the bin/account command in the user directory:
1 * * * * bin/account every day 3:20 A.M. execute two instructions as shown below in user directory (each instruction is delimited):
3 * * * (/bin/rm-f expire.ls logins.bad;bin/expire$#@62;expire.1st)
Each year in January and April, 4th to 9th of 3:12 and 3:55 execute/bin/rm-f expire.1st This command, 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 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 separates] display=:0.0  #加上吧, with a colon with a period.  #    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 points, 4 points, 7 points [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 minutes, plus 3 minutes, until greater than 10==> this is the correct solution for  ] @reboot shutdown -k  now  #这行能把你吓坏, turn off the machine when you turn it on (if you change "-K" to "-H").   "@reboot" means execution at startup.  ---------------------------------END--------------------------------------------  Another script:  ****** ******************* [0-59]/5 23 * * *  shutdown -h now  #每天晚上11点每隔5分钟关一次机, the wish is good, but will not be executed, because the path variable is not set, the workaround is shown below.  [0-59]/5 23 * * * /sbin/shutdown -h now  #保证关得很死, gives the path.  0 6 1 8 * xmms /music/zhangchu/thrashed .mp3  #明天早上6点钟放首歌叫我. But sleep until 7 o'clock still didn't hear music, sad disappointment. [display=:0.0]. The last point of the bank to add: Today 99% motherboards are supported on a timed boot, no alarm clock can call the computer wake you, options in the BIOS power supply [wake up by alarm].  *********************************END*******************************************  can be freely modified, Originally posted on the Linuxsir website.   
Let's take a look at the crontab file for a super User:
#Run the ' Atrun ' program every minutes #This runs anything that's due to Run from ' at '.   See mans ' 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

How to perform tasks with cron at regular intervals under Linux

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.