CentOS7 定时任务

在centos上最常用的定时任务服务是crond。

任务是由 cron (crond) 这个系统服务来控制的,这个系统服务是默认启动的。用户自己设置的计划任务则使用crontab命令。crond和crontab是不可分割的。

1. 安装软件服务

正常centos7自动安装crond服务及crontab,不用安装。如果找不到该服务,则使用命令安装。

# 检查crond服务是否安装
yum list cronie  

# 查看crond服务运行状态
systemctl status crond

# 安装服务
yum install -y cronie crontabs    

这样就行了

2. 关于crond和crondtab常用命令

2.1 crond常用命令

systemctl start   crond         启动服务
systemctl stop    crond         停止服务
systemctl restart crond         重启服务
systemctl reload  crond         重载配置文件
systemctl status  crond         查看状态

2.2 crontab常用命令

crontab -u 		设定某个用户的cron服务
crontab -l		显示crontab文件(显示已设置的定时任务)
crontab -e		编辑crontab文件(编辑定时任务)
crontab -r		删除crontab文件(删除定时任务)
crontab -i		删除crontab文件提醒用户(删除定时任务)

3. 定时任务格式

查看配置文件/etc/crontab

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=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 executed

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

*:表示任意时间都,实际上就是“每”的意思。可以代表00-23小时或者00-12每月或者00-59分
-:表示区间,是一个范围,00 17-19 * * * cmd,就是每天17,18,19点的整点执行命令
,:是分割时段,30 3,19,21 * * * cmd,就是每天凌晨3和晚上19,21点的半点时刻执行命令
/n:表示分割,可以看成除法,*/5 * * * * cmd,每隔五分钟执行一次

4. 三种编辑定时任务的方式

4.1、直接编辑配置文件

配置文件路径:/etc/crontab
在配置文件中,原本6个段的配置,我们需要在命令前面再加一个用户段
即:分 时 日 月 周 用户 命令
直接添加到最后一行即可

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=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 executed
 
 */20 *  *  *  *  root  /usr/sbin/ntpdate pool.ntp.org > /dev/null 2>&1

4.2、使用crontab -e 命令编辑

使用命令编辑相当于就是编辑当前用户的任务,所以不需要加用户字段,这里就是6段

*/20 * * * * /usr/sbin/ntpdate pool.ntp.org > /dev/null 2>&1

4.3、直接编辑目标文件

进入/var/spool/cron/目录,这个目录下的文件都是以用户命名的,文件内容就是用户设置的定时任务。

使用crontab -e 命令添加的任务,都是编写在该文件下。

4.4、实例

* * * * * 				# 每1分钟执行一次
15,30,45 * * * * 		# 每小时的第15、30、45分执行
15,30 10-11 * * * 		# 在上午10点到11点的第15和第30分钟执行
* */2 * * * 			# 每两个小时执行一次

4.5、相关文件

#该文件中所列用户不允许使用crontab命令
	/etc/cron.deny

# 该文件中所列用户允许使用crontab命令
	/etc/cron.allow

#所有用户crontab文件存放的目录,以用户名命名
	/var/spool/cron/

# crond日志文件
	/var/log/cron

 

posted @ 2021-06-18 12:28  两口猪头肉OVO  阅读(573)  评论(0编辑  收藏  举报