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服务

3)  配置定时规则

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,每隔五分钟执行一次

实例

  • */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
原文地址:https://www.cnblogs.com/recordpaperclip/p/15109591.html