linux 系统则是由 cron (crond) 这个系统服务来控制的。Linux 系统上面原本就有非常多的计划性工作,因此这个系统服务是默认启动的。另 外, 由于使用者自己也可以设置计划任务,所以, Linux 系统也提供了使用者控制计划任务的命令 :crontab 命令。
crond 是linux下用来周期性的执行某种任务或等待处理某些事件的一个守护进程,与windows下的计划任务类似,当安装完成操作系统后,默认会安装此服务 工具,并且会自动启动crond进程,crond进程每分钟会定期检查是否有要执行的任务,如果有要执行的任务,则自动执行该任务。
crontab
命令如下:
root@ubuntu:~# crontab --help
crontab: invalid option -- '-'
crontab: usage error: unrecognized option
usage: crontab [-u user] file
crontab [ -u user ] [ -i ] { -e | -l | -r }
(default operation is replace, per 1003.2)
-e (edit user's crontab)
-l (list user's crontab)
-r (delete user's crontab)
-i (prompt before deleting user's crontab)
Linux下的任务调度分为两类,系统任务调度和用户任务调度。系统任务调度:系统周期性所要执行的工作,比如写缓存数据到硬盘、日志清理等。在/etc目录下有一个crontab文件,这个就是系统任务调度的配置文件。/etc/crontab文件包括下面几行:
root@ubuntu:~# cat /etc/crontab
# /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 )
#
前两行是用来配置crond
任务运行的环境变量:
- 第一行
shell
变量指定了系统要使用哪个shell
,这是bash
- 第二行
path
变量指定了系统执行命令的路径!
我们可以新建一个配置文件config.txt
,然后使用它:
crontab config.txt
用户所建立的crontab
配置文件中,每一行都代表一项任务。每行的每一列代表一项设置,它的格式共分为6列,前面1-5列是时间设定列:
m
: 分钟(minute),可以是从0到59之间的任何整数。h
: 小时(hour),可以是从0到23之间的任何整数。dom
: 一个月的第几天(day of month),可以是从1到31之间的任何整数。mon
: 月份(month),可以是从1到12之间的任何整数。dow
: 一个星期的第几天(day of week),可以是从0到7之间的任何整数,这里的0或7代表星期日。
第6列为命令。
举个例子:
0 0 1 * * cat /etc/crontab
这个配置表示,每月1号的0点0分执行cat /etc/crontab
命令
时间设定列,除了会出现数字以外,可能还会出现以下内容:
星号(*)
: 代表所有值,例如mon
设置为*
,那么将表示为频率为每月执行逗号(,)
: 代表指定的一些值,例如mon
设置为1,3,5
,那么将表示为1、3、5月都会执行连字符(-)
: 代表指定的值范围,例如mon
设置为1-3
,那么将表示为1、2、3月都会执行正斜线(/)
: 代表频率间隔,例如minute
设置为0-30/2
,那么表示为0-30分内,每两分钟执行一次。还可以与星号结合,例如minute
设置为*/2
,那么表示为每两分钟执行
安装cron服务
apt-get install cron
cron常见命令:
启动cron服务
service cron start
停止cron服务
service cron stop
重启cron服务
service cron restart
查看cron服务状态
service cron status
常见错误
ubuntu 在执行crond restart 时提示cron: can’t lock /var/run/crond.pid, otherpid may be 2699: Resource temporarily unavailable
解决办法:
rm -rf /var/run/crond.pid
/etc/init.d/cron reload
/etc/init.d/cron restart
自此,Over~~