Linux下定时任务

时间:2022-06-01 21:04:32
   Linux下使用crontab来完成定时任务,这个一般默认安装了,如果没有安装的话自行安装即可,CentOS下面的安装方法为:
yum install crontabs

启动crontab服务:
CentOS 7 以下的启动方法为:

/sbin/service crond start //启动服务
/sbin/service crond stop //关闭服务
/sbin/service crond restart //重启服务
/sbin/service crond reload //重新载入配置

查看crontab服务状态:service crond status
手动启动crontab服务:service crond start
查看crontab服务是否已设置为开机启动,执行命令:ntsysv
加入开机自动启动:
chkconfig –level 35 crond on
CentOS 7及其以上的方法为:

/bin/systemctl start  crond.service
/bin/systemctl stop crond.service
/bin/systemctl restart crond.service
/bin/systemctl reload crond.service

查看服务的状态

/bin/systemctl status  crond.service

crontab命令

功能说明:设置计时器。

语  法:crontab [-u <用户名称>][配置文件] 或 crontab [-u <用户名称>][-elr]

补充说明:cron是一个常驻服务,它提供计时器的功能,让用户在特定的时间得以执行预设的指令或程序。只要用户会编辑计时器的配置文件,就可以使 用计时器的功能。其配置文件格式如下:
Minute Hour Day Month DayOFWeek Command

参  数:
-e  编辑该用户的计时器设置。
-l  列出该用户的计时器设置。
-r  删除该用户的计时器设置。
-u<用户名称>  指定要设定计时器的用户名称。

crontab 格式

基本格式 :

* * * * * command

分 时 日 月 周  命令
第1列表示分钟1~59 每分钟用或者 /1表示
第2列表示小时1~23(0表示0点)
第3列表示日期1~31
第4列 表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要运行的命令

crontab文件的一些例子:

30 23 * * * rm -rf /usr/test/*
每晚的23:30 删除/usr/test/下面的所有资源
30 23 5,10,25 * * rm -rf /usr/test/*
每月5、 10、25 日的23:30 删除/usr/test/下面的所有资源
30 23 * * 6,0 rm -rf /usr/test/*
每周六、周日的23: 30 删除/usr/test/下面的所有资源
0,30 18-23 * * * rm -rf /usr/test/*
每天18 : 00至23 : 00之间每隔30分钟 删除/usr/test/下面的所有资源
30 23 * * 0 rm -rf /usr/test/*
每星期日的23 : 30 删除/usr/test/下面的所有资源
* */1 * * * rm -rf /usr/test/*
每一小时 删除/usr/test/下面的所有资源
* 23-7/1 * * * rm -rf /usr/test/*
晚上11点到早上7点之间,每隔一小时删除/usr/test/下面的所有资源
30 23 10 * mon-wed rm -rf /usr/test/*
每月的10号与每周一到周三的23:30点 删除/usr/test/下面的所有资源
30 23 1 jan * rm -rf /usr/test/*
一月一号的23:30点 删除/usr/test/下面的所有资源
*/30 * * * * rm -rf /usr/test/*
每半小时 删除/usr/test/下面的所有资源
*/20 6-12 * 12 * echo `date`
在12月内,每天的早上6点到12点中,每隔20分钟执行一次echo `date`
0 17 * * 1-5 echo `date`
周一到周五每天下午5:00执行一次echo `date`
20 0-23/2 * * * echo `date`
每天午夜0点到23点,从0:20开始每隔2个小时执行一次echo `date`
0 23-7/2,8 * * * echo `date`
每天晚上11点到早上8点之间每两个小时,以及早上8点执行一次echo `date`
   使用crontab有两种方法,使用crontab -e直接编译脚本和修改/etc/crontab。这两种方法的区别如下:
使用命令 crontab -e 然后直接编辑定时脚本。这样执行以后,属于用户自定义的,会被写到 /var/spool/cron 目录下,生成一个和用户名一致的文件,文件内容就是我们编辑的定时脚本。
[root@soft ~]# ls /var/spool/cron
hadoop root

[root@soft ~]# cat /var/spool/cron/root
0 0 * * * /opt/crontablogclear.sh
   编辑/etc/crontab文件。
[root@soft ~]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# 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
   /etc/crontab是做系统级的配置,crontab -e是用户级的配置,建议使用crontab -e,这样系统也会帮着检查配置的脚本语法。

部分类容参考网络