Chapter 4 scheduled tasks and Chapter 4 tasks

Source: Internet
Author: User
Tags echo command inotify

Chapter 4 scheduled tasks and Chapter 4 tasks

Directory:

12.1 configure scheduled tasks

12.2 crontab file

12.3 crond command debugging

12.4 task plans accurate to seconds

12.1 configure scheduled tasks

Concepts to be clarified first:

(1). crond is a daemon program with the path of/usr/sbin/crond. By default, crond is started later, and crond is started in service or systemd mode by default.

(2). crondtab is a tool for managing crontab files, while crontab file is a file that defines scheduled task entries.

(3 ). crontab file exists in multiple places, including the system scheduled task file/etc/crontab and/etc/cron. d/*, and the task file/var/spool/cron/USERNAME that belongs to each user.

Then the crontab command:

-L: list scheduled task entries-r: delete all task entries in the current task list terminal-I: When deleting an entry, the system prompts whether to delete the entry.-e: edit the scheduled task file, actually, the edited file is/var/spool/cron/*-u: used to operate the scheduled task of a specified user.

Run the crontab-e command to edit the crontab file of the current user. For example, if the current user is a root user, the/var/spool/cron/root file is edited. For example, write the following row.

* * * * * /bin/echo "the first cron entry"  >>/tmp/crond.txt

This will execute the echo command every minute and append the content to the/tmp/crond.txt file.

You can view the/etc/crontab file.

[root@server2 ~]# cat /etc/crontabSHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root # For details see man 4 crontabs # Example of job definition:# .---------------- minute (0 - 59)# |  .------------- hour (0 - 23)# |  |  .---------- day of month (1 - 31)# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# |  |  |  |  |# *  *  *  *  * user-name  command to be executed

This file defines three variables, one of which is PATH, which is extremely important. Finally, the task entry definition method is provided:

(1 ). each task entry is divided into six sections, separated by spaces. Here, the user-name section is added because/etc/crontab is the system scheduled task file, generally, the scheduled task does not have this section.

(2 ). the first five segments are the time set segments, indicating "time-based days, months, and Weeks" respectively. Their definitions cannot exceed the reasonable value range. The sixth segment is the command or script task segment to be executed.

(3) In the time definition section, "*" is used to indicate the number of each unit, namely, every minute, every hour, every day, every month, and every week (still every day ).

(4 ). you can use commas (,) to represent Enumeration During each time period, for example, defining, 50 * indicates that the task is executed for the entire hour, 30th minutes, and 50th minutes.

(5). You can use "-" to define the range in each time period, which can be used with commas. For example, the minute section defines "20th-30, 50" to indicate that the task is executed every minute, 50th to 30 minutes, and minutes at each hour.

(6 ). in each time period, "/" is used to indicate that the time is ignored. For example, if "0-13/2" is defined in a small time period, it means that the time is defined at "0/2/4/6/8/10/12. "*/N" is often used to indicate the interval. For example, "00 */2 ***" indicates that the task is executed every two hours every day.

(7). If the defined day conflicts with Week, the task will be executed multiple times (excluding conflicts caused ). For example, if the task is executed on the 15th day of every month and the task is defined to be executed on Wednesday, the task will be executed on Wednesday and 15th day of every month without any conflict, however, if the 15th day of a month is Wednesday at the same time, the task is executed twice this day. Therefore, efforts should be made to avoid defining weekly and daily tasks at the same time.

(8 ). the percent sign "%" cannot appear at will in the Command segment (that is, the 6th segment), because it represents the special meaning of line feed, and all strings after the first % will be treated as the standard input of the command.

For example, the following definition:

* * * * * /bin/cat >>/tmp/crond.txt %"the first %%cron entry%"

The task outputs the following results:

"the firstcron entry"

Therefore, when defining the file name in a scheduled task entry by time, % should be escaped using a backslash. For example:

* * * * * cp /etc/fstab /tmp/`date +\%Y-\%m-\%d`.txt

Another time period setting that needs to be noted is that using the * number causes the low-level time to overwrite the High-Level time. For example, "**/2 ***" does not mean that a task is executed every two hours, but once every minute. Although it is set every two hours, however, the minute bit is set to every minute, so it still indicates that a task is executed every minute. Similarly, the settings on the "*/5 */2 ***" minute bit overwrite the settings on the hour bit, indicating that the settings are executed every 5 minutes, regardless of the hour bit settings; "00 */2 */5 **" indicates that a task is executed every two hours, regardless of the day number.

12.2 crondtab file

Crondtab file is the task definition file.

(1). In this file, the blank row is ignored. The first behavior comment line that is not blank and starts with #, but # cannot appear in the row.

(2) You can set the environment variable in crontab file by "name = value". Spaces on both sides of the equal sign are free, that is, "name = value" is also allowed. The spaces in the value must be enclosed by quotation marks.

(3) by default, the crond command will Initialize all variables at startup. Except for some variables, crond daemon will automatically set and all other variables will be set to null. The automatically set variables include SHELL =/bin/sh, HOME, and LOGNAME (called USER on CentOS ), the latter two will be set to the value specified in/etc/passwd by default. SHELL and HOME can be overwritten by custom variables in crontab file, but LOGNAME cannot be overwritten. Of course, custom variables will also be loaded into the memory.

(4). In addition to the LOGNAME/HOME/SHELL variable, crond will also look for the MAILTO variable if mail sending is set. If MAILTO is set, the email will be sent to the address specified by this variable. If the value defined by MAILTO is empty (MAILTO = ""), no email will be sent, emails in all other cases are sent to the owner of the crontab file.

(5 ). in the system scheduled task file/etc/crontab, the path environment variables and SHELL environment variables are defined by default. PATH =/sbin:/bin:/usr/sbin: /usr/bin.

(6) crond daemon checks crontab file every minute to check whether there are task plan entries to be executed.

12.3 crond command debugging

Many times, when I write a scheduled task, I find that the task is not executed or fails to be executed. However, crond is running in the background and there are no prompts, which makes troubleshooting difficult. However, crond can be run on the front end and debugged.

First, describe the default execution method of the task scheduler crond.

The following three commands run crond in the background and do not depend on the terminal.

[root@xuexi ~]# systemctl start crond.service[root@xuexi ~]# service crond start[root@xuexi ~]# crond

However, crond allows options to be accepted.

Crond [-n] [-P] [-x flags] Option Description:-n: enables crond to run in the previous terminal mode, that is, it does not depend on the terminal. -P: Do not reset the PATH of the environment variable, but inherit from the parent process. -X: Set debugging items. flags is the debugging method. The useful methods are test and sch, that is, "-x test" and "-x sch ". : The test debugging will not actually be executed, and the sch debugging will be able to see the waiting time. For details, see the following example.

Let's take a look at how the startup script starts crond.

[root@server2 ~]# cat /lib/systemd/system/crond.service[Unit]Description=Command SchedulerAfter=auditd.service systemd-user-sessions.service time-sync.target [Service]EnvironmentFile=/etc/sysconfig/crondExecStart=/usr/sbin/crond -n $CRONDARGSExecReload=/bin/kill -HUP $MAINPIDKillMode=process[Install]WantedBy=multi-user.target

Its Environment configuration file is/etc/sysconfig/crond, and nothing is set in this file.

[root@server2 ~]# cat /etc/sysconfig/crond# Settings for the CRON daemon.# CRONDARGS= :  any extra command-line startup arguments for crondCRONDARGS=

All of its startup commands are:/usr/sbin/crond-n. However, although the "-n" option is added here, crond does not run on the front end and does not depend on the terminal. This is determined by systemctl.

Explain how to perform debugging. The following task entries are used as an example.

[root@server2 ~]# crontab -e* * * * * echo "hello world" >>/tmp/hello.txt

Execute crond with the debugging option test.

[root@server2 ~]# crond -x testdebug flags enabled: test[4903] cron startedlog_it: (CRON 4903) INFO (RANDOM_DELAY will be scaled with factor 8% if used.)log_it: (CRON 4903) INFO (running with inotify support)log_it: (CRON 4903) INFO (@reboot jobs will be run at computer's startup.)log_it: (root 4905) CMD (echo "hello world" >>/tmp/hello.txt )

Execute crond with the debugging option sch.

[Root @ server2 ~] # Crond-x schdebug flags enabled: sch [4829] cron startedlog_it: (CRON 4829) INFO (RANDOM_DELAY will be scaled with factor 73% if used .) log_it: (CRON 4829) INFO (running with inotify support) [4829] GMToff = 28800log_it: (CRON 4829) INFO (@ reboot jobs will be run at computer's startup .) [4829] Target time = 1497950880, sec-to-wait = 38 # wait For crond daemon's next detection, so crond will detect crontab fileuser in 38 seconds [root: 0: 0:...] cmd = "echo" hello world ">/tmp/hello.txt" [4829] Target time = 1497950940, sec-to-wait = 60Minute-ly job. recording time 1497922081log_it: (root 4831) CMD (echo "hello world">/tmp/hello.txt) user [root: 0: 0:...] cmd = "echo" hello world ">/tmp/hello.txt" [4829] Target time = 1497951000, sec-to-wait = 60Minute-ly job. recording time 1497922141log_it: (root 4833) CMD (echo "hello world">/tmp/hello.txt)

However, it should be noted that the waiting time in the sch debugging result is the daemon Detection Time of crond, so it indicates the waiting time for the next detection. Therefore, except for the first time, every time is 60 seconds, because crond detects crontab file once every minute by default. For example, the following is a waiting result. No task is executed during the waiting for detection.

[4937] Target time=1497951720, sec-to-wait=18[4937] Target time=1497951780, sec-to-wait=60[4937] Target time=1497951840, sec-to-wait=60

You can also bring multiple debugging methods at the same time, such:

[root@server2 ~]# crond -x test,schdebug flags enabled: sch test[4914] cron startedlog_it: (CRON 4914) INFO (RANDOM_DELAY will be scaled with factor 21% if used.)log_it: (CRON 4914) INFO (running with inotify support)[4914] GMToff=28800log_it: (CRON 4914) INFO (@reboot jobs will be run at computer's startup.)[4914] Target time=1497951540, sec-to-wait=9user [root:0:0:...] cmd="echo "hello world" >>/tmp/hello.txt "[4914] Target time=1497951600, sec-to-wait=60Minute-ly job. Recording time 1497922741log_it: (root 4916) CMD (echo "hello world" >>/tmp/hello.txt )

In this way, the scheduled task time does not actually execute the command.

12.4 task plans accurate to seconds

By default, crond tasks can only be precise to minutes but not seconds. However, the skill can also be used to implement tasks in seconds.

(1). Method 1: inaccurate Methods

Write a script to sleep3 seconds in the script, so that the command can be executed every 3 seconds.

[root@xuexi ~]# cat /tmp/a.sh#!/bin/bash#PATH="$PATH:/usr/local/bin:/usr/local/sbin"for ((i=1;i<=20;i++));dols /tmpsleep 3done
[root@xuexi ~]# cat /var/spool/cron/lisi* * * * * /bin/bash /tmp/a.sh

However, this method is not the best method, because it takes time to execute the command, and crond has a random Latency by default. The random latency is defined by the variable RANDOM_DELAY.

(2). Method 2: write multiple sleep commands and other commands in the cron configuration file.

[root@xuexi ~]# cat /var/spool/cron/lisi* * * * * ls /tmp* * * * * sleep 3 && ls /tmp* * * * * sleep 6 && ls /tmp* * * * * sleep 9 && ls /tmp* * * * * sleep 12 && ls /tmp* * * * * sleep 15 && ls /tmp* * * * * sleep 18 && ls /tmp* * * * * sleep 21 && ls /tmp* * * * * sleep 24 && ls /tmp* * * * * sleep 27 && ls /tmp* * * * * sleep 30 && ls /tmp…* * * * * sleep 57 && ls /tmp

This method is cumbersome, but more accurate. If it is defined to the level per second, 60 rows of cron records must be written.

It can be seen that the second-level task is not what crond is good. In fact, there are fewer tasks that can be used in seconds.

 

Back to series article outline: http://www.cnblogs.com/f-ck-need-u/p/7048359.html

Reprinted please indicate the source: http://www.cnblogs.com/f-ck-need-u/p/7059418.html

Related Article

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.