Crontab use of Scheduled task commands

Source: Internet
Author: User

Crond Command Introduction

Crond is a daemon that is used to periodically perform certain tasks or wait for certain events under Linux, similar to Scheduled tasks under Windows, when the operating system is installed, the Service tool is installed by default and the Crond process is started automatically. The Crond process periodically checks to see if there is a task to perform and automatically executes the task if there are tasks to perform.

The task scheduling under Linux is divided into two categories, system task scheduling and user task scheduling.

System task scheduling: The work to be performed by the system periodically, such as writing cache data to hard disk, log cleanup, etc. In the/etc directory there is a crontab file, this is the System Task Scheduler configuration file.

The/etc/crontab file includes the following lines:

[[email protected] ~]# cat /etc/crontab shell=/ Bin/bashpath=/sbin:/bin:/usr/sbin:/usr/binmailto=roothome=/# for details see man 4  crontabs# example of job definition:# ---------------- minute  (0  - 59) # |  .------------- hour  (0 - 23) # |  |  &NBSP:---------- day of month  (1 - 31) # |  |  |  &NBSP:------- month  (1 - 12)  OR jan,feb,mar,apr ...# |   |  |  | &NBSP---- day of week  (0 - 6)   ( SUNDAY=0 OR 7)  OR sun,mon,tue,wed,thu,fri,sat# |  |  |   |  |# *  *  *  *  * user-name command  to be executed 

The first four rows are the environment variables that are used to configure the Crond task to run, the shell variable specifies which shell the system will use, this is bash, and the second line of the path variable specifies the path to the System execution command. The third line of the mailto variable specifies that Crond's task execution information will be emailed to the root user, and if the value of the mailto variable is null, the task execution information is not sent to the user, and the home variable in line fourth specifies the home directory to use when executing the command or script.

User Task scheduling: Users to perform regular work, such as user data backup, scheduled email reminders and so on. Users can use the Crontab tool to customize their own scheduled tasks. All user-defined crontab files are saved in the/var/spool/cron directory. Its file name is the same as the user name.

crontab file meaning: In the user's crontab file, each line represents a task, each field of each row represents a setting, its format is divided into six fields, the first five is the time setting segment, the sixth paragraph is the command segment to execute, the format is as follows:

Minute hour day month week User-name
    • Minute: Represents minutes, which can be any integer from 0 to 59.

    • Hour: Represents the hour, which can be any integer from 0 to 23.

    • Day: Represents a date, which can be any integer from 1 to 31.

    • Month: Represents the month, which can be any integer from 1 to 12.

    • Week: Represents the day of the week, which can be any integer from 0 to 7, where 0 or 7 represents Sunday.

    • User-name: User name, if not write, default to the current user.

    • Command: The commands to execute can be either system commands or script files that you write yourself.

In each of these fields, you can also use the following special characters:

    • Asterisk (*): represents all possible values, such as the month field if it is an asterisk, the command action is executed monthly after the constraints of other fields are met.

    • Comma (,): You can specify a list range with a comma-separated value, for example, "1,2,5,7,8,9"

    • Middle Bar (-): An integer range can be represented by a middle bar between integers, such as "2-6" for "2,3,4,5,6"

    • Forward slash (/): You can specify the interval frequency of the time with a forward slash, such as "0-23/2", which is performed every two hours. A forward slash can be used with asterisks, such as */10, if used in the minute field, which means that it executes every 10 minutes.

Crond Command Service

/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

Service Crond Status//view services statuses

Ceondtab command Explanation

1. Command format:

crontab [-u user] File

crontab [-u user] [-e |-l |-r]

2. Command function:

With the crontab command, we can execute specified system instructions or shell script scripts at a fixed interval of time. The units of the time interval can be any combination of minutes, hours, days, months, weeks, and more. This command is very useful for periodic log analysis or data backup.

3. Command parameters:

-u User: Used to set a user's crontab service, for example, "-u ixdba" means to set IXDBA user's crontab service, this parameter is usually run by the root user.

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.

4. Examples of common methods

1 * * * echo "" >/var/log/slow.log

Clear/var/log/slow.log This file every 1:20 A.M.

XX 3 * * 0/bin/sh/usr/local/sbin/backup.sh

Execute "/bin/sh/usr/local/sbin/backup.sh" every Sunday 3 o'clock

4 * */bin/sh/usr/local/sbin/backup_month.sh

14th # 4:10 per month to execute "/bin/sh/usr/local/sbin/backup_month.sh"

XX */8 * * * ntpdate time.windows.com

Perform "Ntpdate time.windows.com" every 8 hours

XX 1,12,18 * * */bin/sh/usr/local/sbin/test.sh

1 points per day, 12 points, 18 points to execute "/bin/sh/usr/local/sbin/test.sh"

XX 09-18 * * */bin/sh/usr/local/sbin/test2.sh

"/bin/sh/usr/local/sbin/test2.sh" is executed from 9 to 18 every day.

The difference between Anacron and cron services:

Cron is used to control the routine work of loop execution, which can be cycled in minutes, hours, weeks, months, or yearly. For example, I want to set up a machine every morning at 8 o ' Day to backup, you can use this service.
Unless our machines are kept open 24 hours a day, there will be some system routine work that no one has done, this time can be used to anacron.
Anacron is not used to replace Cron, Anacron exists for the purpose of the execution of the Cron service that we mentioned above in handling Linux systems that are not 24 hours long-booting! So anacron can not specify when to perform a task, but in days or immediately after the boot Anacron action, he will go to detect the downtime should be carried out but not the cron service, if there is the task to execute once, and then automatically stop.

Extended knowledge using the crontab command:

1. Pay attention to the environment variable problem

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 defining multiple dispatch tasks in a crontab file, one of the issues that needs special attention is the setting of environment variables, because when we perform a task manually, it is done in the current shell environment, the program can certainly find the environment variable, and the system will not load any environment variables when it automatically executes the task schedule. 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.

Don't assume that Cron knows the special circumstances you need, and it doesn't really know. So you have to make sure that you provide all the necessary path and environment variables in the shelll script, except for some auto-set global variables. So note the following 3 points:

1) Write the global path when the file path is involved in the script;

2) When script execution is used in Java or other environment variables, the environment variables are introduced through the source command, such as:

Cat start_cbp.sh

#!/bin/sh

Source/etc/profile

Export run_conf=/home/d139/conf/platform/cbp/cbp_jboss.conf

/usr/local/jboss-4.0.5/bin/run.sh-c MeV &

3) When the script is executed manually, but crontab is not executed. At this point, we must boldly suspect that environmental variables are the bane, and can try to directly introduce environmental variables in crontab to solve the problem. Such as:

0 * * * *. /etc/profile;/bin/sh/var/www/java/audit_no_count/bin/restart_audit.sh

2. Take care to clean up the mail log for 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.

For example, you can set the following form in the crontab file, ignoring the log output:

0 */3 * * */usr/local/apache2/apachectl restart >/dev/null 2>&1

"/dev/null 2>&1" means that the standard output is redirected to/dev/null and then the standard error is redirected to standard output, and standard errors are redirected to/dev/null because the standard output has been redirected to/dev/null. This will solve the problem of log output.

3. System-level task scheduling and user-level task scheduling

System-level task scheduling is mainly to complete some maintenance operations of the system, user-level task scheduling is mainly to complete the user-defined tasks, you can put the user-level task scheduling to the system-level task scheduling to complete (not recommended), but in turn, the root user's task scheduling operation can be through the "crontab– Uroot–e "To set, you can also write the dispatch task directly to the/etc/crontab file, it should be noted that if you want to define a scheduled restart of the system task, you must put the task into the/etc/crontab file, Even the task of creating a timed restart of the system under the root user is not valid.

4. Other precautions

The newly created cron job will not execute immediately, at least 2 minutes. If you restart Cron, it will be executed immediately.

When the crontab suddenly fails, you can try/etc/init.d/crond restart solve the problem. Or check the log to see if a job has execution/error tail-f/var/log/cron.

Don't run crontab-r. It removes the user's crontab file from the crontab directory (/var/spool/cron). All crontab of the user have been deleted.

In Crontab, the% has a special meaning, indicating the meaning of the line break. If you want to use the words must be escaped \%, such as the frequently used date ' +%y%m%d ' in the crontab will not be executed, should be replaced by the date ' +\%y\%m\%d '.

5. Recover the Lost crontab file

If you accidentally delete the crontab file, assuming you have a backup in your own $ H O M directory, you can copy it to/var/spool/cron/<username>, where <username> is the user name. If the copy cannot be completed due to a permissions issue, you can use:

$ crontab <filename>

Where,<filename> is the file name of your copy in the $ H O M e directory.

I recommend that you save a copy of the file in your own $ H O M directory. I have had a similar experience, several times accidentally deleted the crontab file (because the R key is close to the E key to the right). This is why some system documentation does not recommend editing the crontab file directly, but instead edits a copy of the file and then resubmit the new file.

Some variants of crontab are somewhat bizarre, so be careful when using the crontab command. If you omit any of the options, crontab may open an empty file, or it might look like an empty file. Then hit the delete key to exit, do not press <ctrl-d>, otherwise you will lose the crontab file.

Examples of Use:

[Email protected] yuan]# CRONTAB-E
No crontab for root-using an empty one
Crontab:installing New Crontab
[Email protected] yuan]# crontab-l
1-59/2 * * * * echo "jishu*****************"

[Email protected] yuan]# crontab-e-u test1
No crontab for test1-using an empty one
Crontab:installing New Crontab
[Email protected] yuan]# crontab-l-u test1
0-58/2 * * * * echo "even*************"

[Email protected] yuan]# tail-f/var/log/cron
APR 05:23:58 Hpf-linux crontab[1635]: (root) LIST (root)
APR 05:25:01 Hpf-linux crond[1637]: (Root) CMD (echo "jishu*****************")
APR 05:26:24 Hpf-linux crontab[1643]: (Root) BEGIN EDIT (Root)
APR 05:26:37 Hpf-linux crontab[1643]: (Root) END EDIT (Root)
APR 05:26:47 Hpf-linux crontab[1645]: (Root) BEGIN EDIT (test1)
APR 05:27:01 Hpf-linux crond[1648]: (Root) CMD (echo "jishu*****************")
APR 05:27:34 Hpf-linux crontab[1645]: (Root) REPLACE (test1)
APR 05:27:34 Hpf-linux crontab[1645]: (Root) END EDIT (test1)
APR 05:27:46 Hpf-linux crontab[1654]: (Root) LIST (test1)
APR 05:28:01 Hpf-linux crond[1656]: (test1) CMD (echo "even*************")
APR 05:29:01 Hpf-linux crond[1665]: (Root) CMD (echo "jishu*****************")

We use the crontab file name to overwrite the files edited by Crontab-e, while crontab-e the edited file is in/var/spool/cron/root, we can edit the file in the future so that no unnecessary errors will occur.

[Email protected] etc]# CD CRON.D
[[email protected] cron.d]# ls
0hourly Raid-check Sysstat
[email protected] cron.d]# cat Sysstat
# Run System Activity Accounting tool every minutes
*/10 * * * * ROOT/USR/LIB/SA/SA1 1 1
# 0 * * * * ROOT/USR/LIB/SA/SA1 6 &
# Generate a daily summary of process accounting at 23:53
* * * root/usr/lib/sa/sa2-a

[Email protected] cron.d]# crontab-l
1-59/2 * * * * echo "jishu*****************"
You have new mail in/var/spool/mail/root
[Email protected] cron.d]# crontab Sysstat
You have new mail in/var/spool/mail/root
[Email protected] cron.d]# crontab-l
# Run System Activity Accounting tool every minutes
*/10 * * * * ROOT/USR/LIB/SA/SA1 1 1
# 0 * * * * ROOT/USR/LIB/SA/SA1 6 &
# Generate a daily summary of process accounting at 23:53
* * * root/usr/lib/sa/sa2-a

[Email protected] cron.d]# Cat/var/spool/cron/root
# Run System Activity Accounting tool every minutes
*/10 * * * * ROOT/USR/LIB/SA/SA1 1 1
# 0 * * * * ROOT/USR/LIB/SA/SA1 6 &
# Generate a daily summary of process accounting at 23:53
* * * root/usr/lib/sa/sa2-a

In the/ETC/CRON.D directory, the system's scheduled tasks, where edits are not displayed on the user's scheduled tasks but are performed on time.

[Email protected] cron.d]# pwd
/etc/cron.d
[Email protected] cron.d]# VI test1
You have new mail in/var/spool/mail/root
[[email protected] cron.d]# ls
0hourly Raid-check Sysstat test1
[Email protected] cron.d]# tail-f/var/log/cron
APR 05:40:02 Hpf-linux crond[1739]: (Root) CMD (/USR/LIB/SA/SA1 1 1)
APR 05:40:02 Hpf-linux crond[1740]: (test1) CMD (echo "even*************")
APR 05:40:02 Hpf-linux crond[1741]: (Root) CMD (ROOT/USR/LIB/SA/SA1 1 1)
APR 05:42:01 Hpf-linux crond[1753]: (test1) CMD (echo "even*************")
APR 05:44:01 Hpf-linux crond[1764]: (test1) CMD (echo "even*************")
APR 05:46:01 Hpf-linux crond[1770]: (test1) CMD (echo "even*************")
APR 05:48:01 Hpf-linux crond[1781]: (test1) CMD (echo "even*************")
APR 05:50:01 Hpf-linux crond[1794]: (Root) CMD (/USR/LIB/SA/SA1 1 1)
APR 05:50:01 Hpf-linux crond[1795]: (test1) CMD (echo "even*************")
APR 05:50:01 Hpf-linux crond[1796]: (Root) CMD (ROOT/USR/LIB/SA/SA1 1 1)
APR 05:52:01 Hpf-linux crond[1809]: (test1) CMD (echo "even*************")
APR 05:52:01 Hpf-linux crond[1810]: (test1) CMD (echo "File in/etc/cron.d/test1*****8**")
^c
[Email protected] cron.d]# crontab-l-u test1
0-58/2 * * * * echo "even*************"

[Email protected] cron.d]#

Common errors with crontab:

Environment variables

[Email protected] ~]# Vi. bash_profile
[[email protected] ~]# source. bash_profile
[Email protected] ~]# echo $APPDIR
/etc
[Email protected] ~]# CRONTAB-E
Crontab:installing New Crontab
[Email protected] ~]# crontab-l
# Run System Activity Accounting tool every minutes
*/10 * * * * ROOT/USR/LIB/SA/SA1 1 1
# 0 * * * * ROOT/USR/LIB/SA/SA1 6 &
# Generate a daily summary of process accounting at 23:53
* * * root/usr/lib/sa/sa2-a

*/1 * * * * echo $APPDIR >>/tmp/appdir.log

[Email protected] ~]# tail!$
Tail/var/log/cron
APR 06:07:01 Hpf-linux crond[1958]: (Root) CMD (echo $APPDIR >>/tmp/appdir.log)
APR 06:08:01 Hpf-linux crond[1966]: (Root) CMD (echo $APPDIR >>/tmp/appdir.log)
APR 06:08:01 Hpf-linux crond[1967]: (test1) CMD (echo "even*************")
APR 06:08:01 Hpf-linux crond[1968]: (test1) CMD (echo "File in/etc/cron.d/test1*****8**")

[Email protected] ~]# Cat/tmp/appdir.log

The above is not output in the/tmp/appdir.log file, so in this case the Crontab plan considers that the environment variable is not recognized, in the future write the script should pay attention to this problem.

The third and fifth domains perform the actions or operations:

First Sunday in April, 1:59 A.M. run a.sh

Error wording: 1 1-7 4 0/root/a.sh

The regular script was executed at number 1th to 7th, and it was executed every Sunday in April.

1 1-7 4 * test ' date + \%w '-eq 0&&/root/a.sh

Number of minutes set error:

Executes the error every two hours * */2 * * * Date

Correct notation 0 */2 * * * Date

Tips: Execute commands every 0.5s

[Email protected] ~]# crontab-l
# Run System Activity Accounting tool every minutes
*/10 * * * * ROOT/USR/LIB/SA/SA1 1 1
# 0 * * * * ROOT/USR/LIB/SA/SA1 6 &
# Generate a daily summary of process accounting at 23:53
* * * root/usr/lib/sa/sa2-a

*/1 * * * * Date >>/tmp/date.log
*/1 * * * * * sleep 30s;date >>/tmp/date.log

[Email protected] ~]# tail-f/tmp/date.log
Mon APR 06:35:01 CST 2015
Mon APR 06:35:31 CST 2015
Mon APR 06:36:01 CST 2015
Mon APR 06:36:31 CST 2015

Crontab use of Scheduled task commands

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.