计划任务就是设定时间,比如设定5分钟后做什么事情,这样一个计划表。
我们都知道locate 是模糊查找的命令,查找速度还很快,因为其中查找的并不是硬盘而是内置数据库,这个数据库并不是实时更新的,而是每隔一段时间就更新的,这就是用了这个机制。
cron就是计划任务的
[root@nullpointerexception ~]# ps aux |grep cron |grep -v 'grep'
root 5613 0.0 0.0 117204 1376 ? Ss 09:36 0:01 crond
root 6812 0.0 0.0 19396 976 ? Ss 10:01 0:00 /usr/sbin/anacron -s
crond 这个d 表示的是的deamon 服务的进程,一直都在。
/etc/crontab
是它的配置文件
SHELL=/bin/bash 指定了系统要使用哪个shell
PATH=/sbin:/bin:/usr/sbin:/usr/bin 环境变量,系统执行命令的路径
MAILTO=root crond的任务执行信息(执行错误error、info等)将通过电子邮件发送给root用户,如果MAILTO变量的值为空,则表示不发送任务执行信息给用户
HOME=/ 在执行命令或者脚本时使用的主目录
# run-parts 这个参数默认关闭,这样才可以在后边写运行的脚本名,而不是文件夹名
进行计划任务的操作:
[root@nullpointerexception /]# crontab -e
[root@nullpointerexception /]# crontab -l
* * * * * data >> /tmp/test-gsc/10.24/crontab/data.txt
[root@nullpointerexception crontab]# tail /var/log/cron
Oct 24 19:34:02 nullpointerexception CROND[37035]: (root) CMD (date >> /tmp/test-gsc/10.24/crontab/data.txt)
[root@nullpointerexception test]# crontab -r
[root@nullpointerexception test]# crontab -l
no crontab for root
[root@nullpointerexception test]# cat /tmp/test-gsc/10.24/crontab/data.txt
Thu Oct 24 19:34:02 CST 2019
Thu Oct 24 19:35:01 CST 2019
Thu Oct 24 19:36:01 CST 2019
[root@nullpointerexception test]#crontab -u user01 -e
crontab -e 创建计划任务
crontab -l 查看计划任务列表
crontab -r 删除所有的计划任务
crontab -u 用户 -e 用户的计划任务。
tail /var/log/cron 查看日志文件,有新纪录。
这个计划任务可以灵活的对每个用户进行约束,产生的文件在这个目录:
/var/spool/cron/
计划任务分为系统层面的计划任务和用户层面的计划任务,系统层面的计划任务在/etc/crontab
;用户层面的是在/var/spool/cron/tabs
下 ,有计划任务的用户每个用户一个文件
# 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
分钟 小时 天(日) 月 星期
00 02 * * * ls //每天2:00整
00 02 1 * * ls //每月1号2:00整
00 02 14 2 * ls //每年2月14号2:00整
00 02 * * 7 ls //每周日2:00整 0-6表示周一到周日
00 02 * 6 5 ls //每年6月的周五2:00整
00 02 14 * 7 ls //每月14号2:00整 或者 每周日2:00整,这两个时间都执行
00 02 14 2 7 ls //每年2月14号2:00整 或者 每周日2:00整,这两个时间都执行
上边的字段,分钟、小时、天、月、星期是可以用特殊字符的。
星号 *
:代表所有可能的值,例如分钟
的字段如果是星号,则表示在满足其它字段的制约条件下,每分钟都执行该命令操作。
逗号 ,
:枚举,例如,“1,2,5,7,8,9”
中杠 -
:横杠表示一个范围,例如“2-6”表示“2,3,4,5,6”
正斜杠 /
:指定时间的间隔频率,例如0-23/2
表示每两小时
执行一次。同时正斜线可以和星号一起使用,例如*/10
,如果用在分钟
字段,表示每十分钟
执行一次。
注:另外有几个文件:
1、cron.deny
/etc/cron.deny 这个文件里的用户不允许使用crontab命令,黑名单
如果在这里有一个用户ggmm
那么这个用户就不能用计划任务
2、cron.allow
/etc/cron.allow 这个文件里的用户允许使用crontab命令,白名单
在这里有的用户才能使用crontab,没写的全都不能使用。当然root除外。
allow的优先级要高于deny。
如果在deny和allow中都写,是可以使用crontab的。