Linux创建定时任务

本文详细介绍了在CentOS7中如何安装、配置crontab服务,以及如何设置不同频率的定时任务,包括分钟、小时、每日、每周和每年的执行规则,提供实例演示。
摘要由CSDN通过智能技术生成

创建定时任务

CentOS 7 定时任务设置(时间同步)

1. 说明

​ centos7设置定时计划任务,可以利用crontab 来执行计划任务, 依赖与 crond 的系统服务,这个服务是系统自带的,可以直接查看状态,启动,停止。

2.操作

1)安装 crontabs服务

yum install crontabs

2)crontabs命令

systemctl status  crond  //查看状态
systemctl enable  crond //设为开机启动
systemctl start   crond  //启动crond服务systemctl stop    crond //关闭crond服务systemctl restart crond //重启crond服务
  1. 配置定时规则
vim /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,每隔五分钟执行一次

crontab每分钟定时执行:
*/1 * * * * service mysqld restart //每隔1分钟执行一次
*/10 * * * * service mysqld restart //每隔10分钟执行一次
 
crontab每小时定时执行:
0 */1 * * * service mysqld restart //每1小时执行一次
0 */2 * * * service mysqld restart //每2小时执行一次
 
crontab每天定时执行:
0 10 * * * service mysqld restart //每天10点执行
30 19 * * * service mysqld restart //每天19点30分执行
 
crontab每周定时执行:
0 10 * * 1 service mysqld restart //每周一10点执行
30 17 * * 5 service mysqld restart //每周五17点30分执行
 
crontab每年定时执行:
0 10 1 10 * service mysqld restart //每年的10月1日10点执行
0 20 8 8 * service mysqld restart //每年的8月8日20点执行

3.实例

  • */30 * * * root /usr/sbin/ntpdate ntp1.aliyun.com (每天,每30分钟执行一次命令)

  • * 3 * * * root /usr/sbin/ntpdate ntp1.aliyun.com (每天凌晨三点,执行命令脚本,PS:这里由于第一个的分钟没有设置,那么就会每天凌晨3点的每分钟都执行一次命令)

  • 0 3 * * * root /usr/sbin/ntpdate ntp1.aliyun.com (这样就是每天凌晨三点整执行一次命令脚本)

  • */10 11-13 * * * root /usr/sbin/ntpdate ntp1.aliyun.com (每天11点到13点之间,每10分钟执行一次命令脚本)

  • 10-30 * * * * root /usr/sbin/ntpdate ntp1.aliyun.com (每小时的10-30分钟,每分钟执行一次命令脚本,共执行20次)

  • 10,30 * * * * * root /usr/sbin/ntpdate ntp1.aliyun.com (每小时的10,30分钟,分别执行一次命令脚本,共执行2次)

4)保存生效

crontab /etc/crontab

5)查看任务

crontab -l

6)查看日志

tail -f /var/log/cron
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值