Linux任务调度分为两类:
系统任务调度和用户任务调度。
1. 系统任务
系统周期性所要执行的工作,如备份系统数据、清理缓存。
系统cron任务调度文件存放在/etc/crontab
和/etc/cron.d
目录下。而且只有root用户才能操作。
一般我们不去操作系统任务,而是根据需求创建用户任务。
例子:
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user command
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
2. 用户任务
用户定期想要处理的任务,如每个30分钟点击网站。
每个用户(包括root用户)都有属于自己的cron任务调度文件。
通过crontab -e
创建的cron文档存放在/var/spool/cron
目录下
例子:
0 10 * * * (/srv/scrapy/runrightmove.sh)
0 22 * * * (/srv/scrapy/runrightmove.sh)
3. cron服务
在Ubuntu16.04版本从
crond
变成了cron
。每分钟会定期检查是否有需要执行的文档,如有则执行。
查看服务
service cron status
3.1 crontab命令
crontab是用来创建定时任务的命令
语法:
crontab [ -u user ] { -l | -r | -e }
- 如省略用户则代表是当前用户
命令:
-
列出crontab文件
crontab -l
-
编辑crontab文件
crontab -e
-
删除crontab文件
crontab -r
3.2 crontab执行文件
在执行文档中,主要分为两部分,第一部分是执行时间。第二部分是执行命令,执行命令就是shell指令,要执行的内容。
#minute hour day month week command
* * * * * command
3.2.1 执行时间
minute
: 表示分钟,范围0~59 hour
:表示小时,范围0~23 day
:表示日期,范围1~31 month
:表示月份,范围1~12 week
:表示星期几,范围0~7。这里的0或7代表星期日。 command
:要执行的命令,可以是系统命令,也可以是自己编写的脚本文件。
- 时间
*
代表当前时间刻度的最小单位。eg:在minute处代表每分钟,在hour处代表每小时。,
代表是一个数组(含有若干个时间刻度),格式<number>,<number>,<number>
。eg:1,2,5,6
在分钟。代表分别在1,2,5,6分时执行-
代表range范围,格式<number>-<number>
(多个range可用,
隔开)。eg:0-12
小时。代表在0-12
点时执行/
代表间隔时间,格式/<number>
。eg:*/2
在小时。代表每隔2小时执行
month
和week
可以用前3个英文字母代表。eg:mon, feb, fri, jan, dec
关于时间的例子:
1.每分钟执行一次
* * * * * command
2.每小时的0分、30分执行
0,30 * * * * command
3. 在8点至17点的15分、45分执行
15,45 8-17 * * * command
4.每周五的12点15分执行
15 12 * * 5 command
5.每两天执行
* * */2 * * command
6.每月1,15号的0时0分执行
0 0 1,15 * * command
3.2.2 执行命令
可执行单条命令或者是脚本文件
3.2.3 任务日志重定向到指定地方
cron运行的每一项计划任务都会被记录到/var/log/cron
文件中,有时我们希望将某一任务的日志放到指定的地方去,如下样例:
$ 30 10 * * * command >> /srv/logs/xxx.log 2>&1
-
日志重定向的时候要注意,将标准错误日志一起重定向,才能获取到正常和错误的日志。
2>&1
,表示将错误的日志(文件描述符为2)重定向到标准输出(文件描述符为1)中。 -
如果想按照日期生成日志,则可写成
$ 30 10 * * * command >> "/srv/logs/$(date +"\%Y-\%m").log" 2>&1
3. 查看任务执行情况
查看定时任务是否执行
通过查看系统日志来确认。
$ cat /var/log/syslog | grep CRON
There are 0 comments