Centos7 计划任务

at

一次性计划任务

1.创建一次性计划任务

[fwj@rhca ~]$ at 14:18
at> ping www.baidu.com >> /opt/baidu
at> ^C[fwj@rhca ~]$ at 14:18
at> ping www.baidu.com >> /opt/baidu<EOT>
job 3 at Sun Apr 23 14:18:00 2017

输入 ctrl+d 保存退出

2.查看

[fwj@rhca ~]$ atq
3    Sun Apr 23 14:18:00 2017 a fwj
[fwj@rhca ~]$

3.删除

[root@rhca ~]# atrm 4
[root@rhca ~]# atq

crontab

1.查看服务状态

[root@rhca ~]# systemctl status crond.service
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2017-04-23 14:16:31 CST; 4min 28s ago
 Main PID: 1173 (crond)
   CGroup: /system.slice/crond.service
           └─1173 /usr/sbin/crond -n

Apr 23 14:16:31 rhca systemd[1]: Started Command Scheduler.
Apr 23 14:16:31 rhca systemd[1]: Starting Command Scheduler...
Apr 23 14:16:31 rhca crond[1173]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 28% if used.)
Apr 23 14:16:34 rhca crond[1173]: (CRON) INFO (running with inotify support)

###主要配置文件

  • 全局配置文件:/etc/crontab
  • 系统默认的设置: /etc/cron.*/
  • 用户定义的设置: /var/spool/cron/user

格式

# 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

计划任务格式

* * * * * user-name command to be executed

前面5列分别代表:

  • 第一列表示分 0-59
  • 第二列表示时 0-23
  • 第三列表示天 1-31
  • 第四列表示月 1-12
  • 第七列(可选)表示用户
  • 第八列 表示需要执行的具体脚本或命令的绝对路径

通配符

  • *表示任意时间
  • ,表示多个不连续的时间点
  • -表示一个连续的时间范围
  • /表示间隔的时间频率

查看列表

[root@rhca ~]# crontab -l
*/1 * * * * root /usr/bin/ping awen.com >> /opt/www
[root@rhca ~]# tail -f /var/log/cron
cron           cron-20170423

查看日志

[root@rhca ~]# tail -f /var/log/cron
Apr 23 14:44:26 rhca crontab[12788]: (root) BEGIN EDIT (root)
Apr 23 14:44:36 rhca crontab[12788]: (root) REPLACE (root)
Apr 23 14:44:36 rhca crontab[12788]: (root) END EDIT (root)
Apr 23 14:44:41 rhca crontab[12792]: (root) LIST (root)
Apr 23 14:44:44 rhca crontab[12794]: (root) BEGIN EDIT (root)
Apr 23 14:44:55 rhca crontab[12794]: (root) REPLACE (root)
Apr 23 14:44:55 rhca crontab[12794]: (root) END EDIT (root)
Apr 23 14:45:00 rhca crontab[12798]: (root) LIST (root)
Apr 23 14:45:01 rhca crond[1173]: (root) RELOAD (/var/spool/cron/root)
Apr 23 14:45:01 rhca CROND[12804]: (root) CMD (root /usr/bin/ping awen.com >> /opt/www)

案例

编辑计划任务

crontab -e

附:crontab规则详细实例

1.每天6:00执行

0 6 * * * root/root/root.sh

2.每周六凌晨4:00执行

0 4 * * 6 root /root/root.sh

3.每周六凌晨4:05执行

5 4 * * 6 root /root/root.sh

4.每周六凌晨4:15执行

15 4 * * 6 root /root/root.sh

5.每周六凌晨4:25执行

25 4 * * 6  root /root/root.sh

6.每周一到周五的11:41开始,每10分钟执行一次

1-59/10 12-23 * * 1-5 root /root/root.sh

7.每天的10:31开始,每隔2小时执行一次

31 10-23/2 * * * root /root/root.sh