我们有时候需要服务器自动更新或者定时间运行某个程序或或者脚本

需要用到crontabs

  1. 可以先查看一下当前机器上是否已经安装了crontabs
[root@localhost ~]# rpm -qa| grep crontabs
crontabs-1.11-6.20121102git.el7.noarch

2.如果没有需要利用yum 进行安装

[root@localhost ~]# yum install crontabs
3.启动服务
#启动
/bin/systemctl restart crond.service
[root@localhost terry]# systemctl status crond.service
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: active (running) since Wed 2016-07-13 21:12:05 CST; 55min ago
 Main PID: 1456 (crond)
   CGroup: /system.slice/crond.service
           └─1456 /usr/sbin/crond -n

Jul 13 21:12:05 localhost.localdomain systemd[1]: Started Command Scheduler.
Jul 13 21:12:05 localhost.localdomain systemd[1]: Starting Command Scheduler...
Jul 13 21:12:05 localhost.localdomain crond[1456]: (CRON) INFO (RANDOM_DELAY ...
Jul 13 21:12:05 localhost.localdomain crond[1456]: (CRON) INFO (running with ...
Hint: Some lines were ellipsized, use -l to show in full.

#重新载入配置

/bin/systemctl reload  crond.service

#查看crontab服务状态

/bin/systemctl status  crond.service

4.查看计划任务。基本命令行参数建议使用crontab --help查看

#查看当前用户计划任务

crontab -l
[root@localhost ~]# crontab -l
no crontab for root

#查看userx用户的计划任务

crontab -u userx -l
[root@localhost ~]# crontab -u terry -l
no crontab for terry
[root@localhost ~]#

5.查看日志

tail -f /var/log/cron

6./etc/crontab文件里面存放系统计划任务,/var/spool/cron/目录里面按用户存放计划任务。

7./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
下面添加具体任务
举例(来自网络):
30 21 * * * /usr/local/etc/rc.d/apache restart  #每晚的21:30 重启apache

45 4 1,10,22 * * /usr/local/etc/rc.d/apache restart  #每月1、10、22日的4 : 45重启apache

10 1 * * 6,0 /usr/local/etc/rc.d/apache restart #每周六、周日的1 : 10重启apache

0,30 18-23 * * * /usr/local/etc/rc.d/apache restart  #每天18 : 00至23 : 00之间每隔30分钟重启apache

0 23 * * 6 /usr/local/etc/rc.d/apache restart  #每星期六的11 : 00 pm重启apache

* 23-7/1 * * * /usr/local/etc/rc.d/apache restart  #晚上11点到早上7点之间,每隔一小时重启  apache

* */1 * * * /usr/local/etc/rc.d/apache restart  #每一小时重启apache

0 11 4 * mon-wed /usr/local/etc/rc.d/apache restart #每月的4号与每周一到周三的11点重启apache

0 4 1 jan * /usr/local/etc/rc.d/apache restart  #一月一号的4点重启apache

*/30 * * * * /usr/sbin/ntpdate 210.72.145.44  #每半小时同步一下时间