Directory of this article:
##12.1 Configuring scheduled tasks
12.2 crontab file
12.3 Debugging of crond command
12.4 Task planning accurate to seconds
12.1 Configuring scheduled tasksThe concepts that need to be understood first:
(1).crond is a daemon class program, the path is /usr/sbin/crond. By default, it will be started in the background mode. When crond is started in service or systemd mode, it will also be started in the background mode by default. (2).crondtab is a tool for managing crontab files, and crontab file is a file that defines scheduled task entries. (3).crontab file exists in many places, including system scheduled task files /etc/crontab and /etc/cron.d/*, as well as task files unique to each user /var/spool/ cron/USERNAME. Then there is the crontab command:-l:列出定时任务条目 -r:删除当前任务列表终端所有任务条目 -i:删除条目时提示是否真的要删除 -e:编辑定时任务文件,实际上编辑的是/var/spool/cron/*文件 -u:操作指定用户的定时任务Execute the crontab -e command to edit the crontab file of the current user. For example, if you are currently the root user, edit is the /var/spool/cron/root file. For example, write the following line.
* * * * * /bin/echo "the first cron entry" >>/tmp/crond.txtThis will execute the echo command every minute and append the content to the /tmp/crond.txt file. How to define the task entries in the task plan, you can view the /etc/crontab file.
[root@server2 ~]# cat /etc/crontab SHELL=/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 executedThere are 3 variables defined in this file, one of which is PATH, which is extremely important. At the end, the definition method of task entries is also given: (1). Each task entry is divided into 6 sections, each section is separated by spaces. The reason why there is an extra user-name section here is because/ etc/crontab is the system scheduled task file, and general scheduled tasks do not have this section. (2). The first five paragraphs are the time setting periods, which respectively represent "time, day, month and week". Their definitions cannot exceed the reasonable value range. The sixth paragraph is the command or script task to be executed. part. (3). In the time definition section, use "*" to indicate each unit, that is, every minute, every hour, every day, every month, and the day of the week (still every day). (4). In each time period, you can use commas "," to represent enumerations. For example, define "0,30,50 * * * *" to represent the hour and hour of each hour. This task is performed at both the 30th and 50th minutes. (5). In each time period, you can use "-" to define the range, which can be used in combination with commas. For example, if the minute segment is defined as "00,20-30,50", it means that the task will be executed on the hour, every minute from the 20th to the 30th minute, and the 50th minute. (6). In each time period, use "/" to indicate ignoring the time. For example, if "0-13/2" is defined in the small period, it means "0/2/4/6/8/ The 10/12" point meets the time definition. "*/N" is often used to indicate how often. For example, "00 */2 * * *" means to execute the task on the hour every two hours every day. (7). If the defined day and week conflict, it will be executed multiple times (excluding conflicts caused by the * sign). For example, the task is executed on the 15th of each month, and the task is also defined to be executed on Wednesday. Under normal circumstances without conflict, it will be executed on Wednesday and the 15th of each month. However, if the 15th of a certain month is also a Wednesday, the task will be executed on Wednesday. Executed twice this day. Therefore, you should try to avoid tasks that define both week and day at the same time.
(8). In the command paragraph (i.e. paragraph 6), the percent sign "%" cannot appear arbitrarily, because it represents the special meaning of line break, and all characters after the first % The string 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 output result of this task will be:
"the firstcron entry"So, when defining the file name with time in the scheduled task entry, % should be escaped with a backslash. For example:
* * * * * cp /etc/fstab /tmp/`date +\%Y-\%m-\%d`.txt
Another time period setting that needs attention is that using the * sign causes low-level time to overwrite high-level time. For example, "* */2 * * *", it does not mean to execute the task every two hours, but every minute. Although the hour bit is set to every two hours, the minute bit is set to every minute. , so it still means that the task is executed every minute. In the same way, the setting on the minute digit of "*/5 */2 * * *" overrides the setting on the hour digit, indicating that it is executed every 5 minutes and ignores the setting of the hour digit; "00 */2 */5 * *" Indicates that the task will be executed every two hours on the hour regardless of the day setting.
12.2 crondtab file
crondtab file为任务定义文件。
(1).在此文件中,空行会被忽略,首个非空白字符且以#开头的行为注释行,但#不能出现在行中。
(2).可以在crontab file中设置环境变量,方式为"name=value",等号两边的空格可随意,即"name = value"也是允许的。但value中出现的空格必须使用引号包围。
(3). 默认crond命令启动的时候会初始化所有变量,除了某几个变量会被crond daemon自动设置好,其他所有变量都被设置为空值。自动设置的变量包括SHELL=/bin/sh,以及HOME和LOGNAME(在CentOS上则称为USER),后两者将被默认设置为/etc/passwd中指定的值。其中SHELL和HOME可以被crontab file中自定义的变量覆盖,但LOGNAME不允许覆盖。当然,自行定义的变量也会被加载到内存。
(4).除了LOGNAME/HOME/SHELL变量之外,如果设置了发送邮件,则crond还会寻找MAILTO变量。如果设置了MAILTO,则邮件将发送给此变量指定的地址,如果MAILTO定义的值为空(MAILTO=""),将不发送邮件,其他所有情况邮件都会发送给crontab file的所有者。
(5).在系统定时任务文件/etc/crontab中,默认已定义PATH环境变量和SHELL环境变量,其中PATH=/sbin:/bin:/usr/sbin:/usr/bin。
(6).crond daemon每分钟检测一次crontab file看是否有任务计划条目需要执行。
12.3 crond命令的调试
很多时候写了定时任务却发现没有执行,或者执行失败,但因为crond是后台运行的,有没有任何提示,很难进行排错。但是可以让crond运行在前端并进行调试的。
先说明下任务计划程序crond的默认执行方式。
使用下面三条命令启动的crond都是在后台运行的,且都不依赖于终端。
[root@xuexi ~]# systemctl start crond.service [root@xuexi ~]# service crond start [root@xuexi ~]# crond
但crond是允许接受选项的。
crond [-n] [-P] [-x flags] 选项说明:-n:让crond以前端方式运行,即不依赖于终端。-P:不重设环境变量PATH,而是从父进程中继承。-x:设置调试项,flags是调试方式,比较有用的方式是test和sch,即"-x test"和"-x sch"。 :其中test调试将不会真正的执行,sch调试将可以看到等待时间。具体的见下面的示例。
先看看启动脚本启动crond的方式。
[root@server2 ~]# cat /lib/systemd/system/crond.service [Unit] Description=Command Scheduler After=auditd.service systemd-user-sessions.service time-sync.target [Service]EnvironmentFile=/etc/sysconfig/crond ExecStart=/usr/sbin/crond -n $CRONDARGSExecReload=/bin/kill -HUP $MAINPID KillMode=process [Install] WantedBy=multi-user.target
它的环境配置文件为/etc/sysconfig/crond,该文件中什么也没设置。
[root@server2 ~]# cat /etc/sysconfig/crond # Settings for the CRON daemon. # CRONDARGS= : any extra command-line startup arguments for crond CRONDARGS=
所有它的启动命令为:/usr/sbin/crond -n。但尽管此处加了"-n"选项,crond也不会前端运行,且不会依赖于终端,这是systemctl决定的。
在解释下如何进行调试。以下面的任务条目为例。
[root@server2 ~]# crontab -e* * * * * echo "hello world" >>/tmp/hello.txt
执行crond并带上调试选项test。
[root@server2 ~]# crond -x test debug flags enabled: test [4903] cron started log_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 )
执行crond并带上调试选项sch。
[root@server2 ~]# crond -x sch debug flags enabled: sch [4829] cron started log_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 # 等待crond daemon下一次的检测,所以表示38秒后crond将检测crontab file user [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 )
但要注意,在sch调试结果中的等待时间是crond这个daemon的检测时间,所以它表示等待下一次检测的时间,因此除了第一次,之后每次都是60秒,因为默认crond是每分钟检测一次crontab file的。例如,下面是某次的等待结果,在这几次等待检测过程中没有执行任何任务。
[4937] Target time=1497951720, sec-to-wait=18[4937] Target time=1497951780, sec-to-wait=60[4937] Target time=1497951840, sec-to-wait=60
还可以同时带多个调试方式,如:
[root@server2 ~]# crond -x test,schdebug flags enabled: sch test[4914] cron started log_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=9 user [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 )
这样在调试定时任务时间时,也不会真正执行命令。
12.4 精确到秒的任务计划
默认情况下,crond执行的任务只能精确到分钟,无法精确到秒。但通过技巧,也是能实现秒级任务的。
(1).方法一:不太精确的方法
写一个脚本,在脚本中sleep3秒钟的时间,这样能实现每3秒执行一次命令。
[root@xuexi ~]# cat /tmp/a.sh#!/bin/bash # PATH="$PATH:/usr/local/bin:/usr/local/sbin"for ((i=1;i<p class="cnblogs_code"></p><pre class="brush:php;toolbar:false">[root@xuexi ~]# cat /var/spool/cron/lisi* * * * * /bin/bash /tmp/a.sh
但是这样的方法不是最佳方法,因为执行命令也需要时间,且crond默认会有一个随机延时,随机延时由变量RANDOM_DELAY定义。
(2).方法二:在cron配置文件中写入多条sleep命令和其他命令。
[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
这种方式很繁琐,但是更精确。如果定义到每秒级别就得写60行cron记录。
由此能看出,秒级的任务本就不是crond所擅长的。实际上能用到秒级的任务也比较少。
The above is the detailed content of Linux explanation of scheduled tasks. For more information, please follow other related articles on the PHP Chinese website!

The default storage location of Apache server log files in Debian system: Access log: usually located in /var/log/apache2/access.log. Error log: Usually located in /var/log/apache2/error.log. It should be noted that the above path is the default configuration of Apache. You can change the storage location of the log file by modifying the Apache configuration file /etc/apache2/apache2.conf or related environment variables.

This article introduces several methods to monitor Tomcat log exceptions to help you discover and solve problems in a timely manner and ensure the stable operation of the application. 1. Using ELK stack to achieve centralized monitoring. It is recommended to use ELK (Elasticsearch, Logstash, Kibana) stack for efficient log monitoring. Data acquisition (Filebeat): Configure Filebeat to collect warning (WARN) and error (ERROR) levels in Tomcat log files (such as catalina.out). Logstash: Logstash preprocesses collected logs, such as filtering, parsing and conversion. Data storage

This article introduces several effective ways to free up disk space in Debian systems. Be sure to back up important data before performing any actions. 1. Volume management: Check disk usage: Use vgs and pvs commands to check the usage of volume groups and physical volumes. Delete useless logical volumes: Use the lvremove command to delete logical volumes that are no longer needed. For example: sudolvremove/dev/mapper/debianOA--vg-lv_data (please replace it with the actual logical volume path). 2. Package management: Uninstall useless software: Use the apt-getautoremove command to automatically uninstall the no longer needed software packages and their

Strengthening the security of DebianApache server logs requires collaborative efforts from multiple aspects. The following strategies can effectively reduce security risks: 1. Log monitoring and analysis Automated log analysis: Use logcheck, logrotate and other tools to regularly check and analyze logs to promptly detect suspicious activities and potential attacks. Real-time monitoring system: Establish a log monitoring system, such as ELKStack (Elasticsearch, Logstash, Kibana), to realize real-time monitoring and analysis of log data. 2. Strict permission settings for log file permissions: Reasonably set log file permissions, such as using chmod640/var/log

The Nginx server log records various client request information. This article will introduce in detail the common request types and related information in the Nginx log. 1. HTTP request method Nginx log records a variety of HTTP request methods, which are used to indicate the way clients interact with the server: GET: the most commonly used request method, which is used to obtain data from the server, such as web pages, pictures, CSS files, etc. Request parameters are usually included in the URL. POST: is used to submit data to the server, often used for form submission or file upload. Data is contained in the request body, not the URL. PUT: Used to upload files or update existing resources on the server. The data is also located in the request body. DEL

This article describes how to clean up package dependencies that are no longer needed in the Debian system. Please be careful and it is recommended to back up important data. Step 1: Update the package list First, update your package list to make sure the information is up to date: sudoaptupdate Step 2: Identify useless dependencies Use the apt-rdepends command to find which packages depend on the package you want to delete (for example package_name): apt-rdependspackage_name|grep-v"^"|sort-u This command lists all packages that depend on package_name, but does not include package_name

This article introduces how to configure Apache log rotation in the Debian system, mainly using the logrotate tool. Step 1: Verify whether logrotate is installed. Check with the following command: logrotate--version If not installed, execute: sudoapt-getupdatesudoapt-getinstalllogrotateStep 2: Locate the Apache log rotation configuration file. The configuration file is usually located in the /etc/logrotate.d/ directory. The file name may be apache2 or httpd. Use the following command to find: ls/etc/logrot

This article describes how to effectively clean up old versions of software and kernels in Debian systems, free up disk space and improve system performance. Be sure to back up important data before operation. 1. Clear useless packages. Use the apt command line tool to easily delete no longer needed software packages and their dependencies: open the terminal. Execute the sudoapt-getautoremove command to automatically delete redundant dependencies of installed packages. Use the sudoapt-getpurge command to delete the specified package and its configuration files. For example, delete firefox and its configuration files and execute sudoapt-getpurgefirefox.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version
God-level code editing software (SublimeText3)