crond定时任务

1、定时任务服务的查看、启动和关闭

systemctl start crond    开启定时任务
systemctl stop crond    关闭定时任务
systemctl status crond    查看定时任务的状态
systemctl disable crond    设置定时任务开机不自启
systemctl enable crond     设置定时任务开机自启

2、定时任务的编写
使用crontab -e来编写定时任务,实际是在编写/var/spool/cron/root这个文件
crontab -l 查看定时任务
crontab -r 清除定时任务
crontab -u 指定定时任务的用户

3、定时任务的编写规范

[root@localhost ~]# vim /etc/crontab
SHELL=/bin/bash                     #执行命令的解释器
PATH=/sbin:/bin:/usr/sbin:/usr/bin  #环境变量
MAILTO=root                         #邮件发给谁
# 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  #星期
# |  |  |  |  |
# *  *  *  *  *   command to be executed

# *  表示任意的(分、时、日、月、周)时间都执行
# -  表示一个时间范围段, 如5-7点
# ,  表示分隔时段, 如6,0,4表示周六、日、四
# /1 表示每隔n单位时间, 如*/10 每10分钟


00 02 * * * ls      #每天的凌晨2点整执行
00 02 1 * * ls      #每月的1日的凌晨2点整执行
00 02 14 2 * ls     #每年的2月14日凌晨2点执行
00 02 * * 7 ls      #每周天的凌晨2点整执行
00 02 * 6 5 ls      #每年的6月周五凌晨2点执行
00 02 14 * 7 ls     #每月14日或每周日的凌晨2点都执行
00 02 14 2 7 ls     #每年的2月14日或每年2月的周天的凌晨2点执行   
*/10  02 * * * ls   #每天凌晨2点,每隔10分钟执行一次
* * * * *  ls       #每分钟都执行
00 00 14 2 *  ls    #每年2月14日的凌晨执行命令 
*/5 * * * *  ls     #每隔5分钟执行一次
00 02 * 1,5,8 * ls  #每年的1月5月8月凌晨2点执行
00 02 1-8 * *  ls    #每月1号到8号凌晨2点执行
0 21 * * * ls       #每天晚上21:00执行
45 4 1,10,22 * * ls #每月1、10、22日的4:45执行
45 4 1-10 * * l     #每月1到10日的4:45执行
3,15 8-11 */2 * * ls #每隔两天的上午8点到11点的第3和第15分钟执行
0 23-7/1 * * * ls   #晚上11点到早上7点之间,每隔一小时执行
15 21 * * 1-5 ls    #周一到周五每天晚上21:15执行
  1. 给定时任务设置黑名单
使用root将需要拒绝的用户加入/etc/cron.deny
[root@localhost.localdomain /etc]# echo 'hax' >> /etc/cron.deny 
切换到hax用户
[root@localhost.localdomain /etc]# su - hax
使用crontab -e编写定时任务,提示不能编写
[hax@localhost.localdomain ~]$ crontab -e
You (hax) are not allowed to use this program (crontab)
See crontab(1) for more information
  1. 定时任务日志
    定时任务日志存在于/var/log/cron
[root@localhost.localdomain ~]# tail -f /var/log/cron
Nov  9 16:10:01 localhost CROND[2836]: (root) CMD (ntpdate time.windows.com &>/dev/null)
Nov  9 16:11:01 localhost CROND[2843]: (root) CMD (ntpdate time.windows.com &>/dev/null)
Nov  9 16:12:01 localhost CROND[2848]: (root) CMD (ntpdate time.windows.com &>/dev/null)
Nov  9 16:13:01 localhost CROND[2853]: (root) CMD (ntpdate time.windows.com &>/dev/null)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。