crontab定时任务

1.计划任务基本概述

1.1什么是crond

crond就是计划任务,类似于我们平时生活中的闹钟。定点执行.

1.2为什么需要crond

crond主要是做一些周期性的任务

场景1: 定期备份重要的文件或数据。

场景2: 促销活动,准点开启抢购接口,准点关闭抢购接口。

场景3: 每分钟检测超时订单,超过30分钟未支付的订单进行取消。

场景4: 每隔5分钟上各个电商平台刷取订单信息写入自己公司的系统中

1.3计划任务两大类

1.系统级别的定时任务:临时文件清理、系统信息采集、日志文件切割

2.用户级别的定时任务:定时备份数据,同步时间,订单超时自动取消,按时间段统计信息等等

2计划任务的基本应用

2.1计划任务时间周期

Crontab配置文件记录了时间周期的含义

[root@localhost ~]# cat  /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
#*表示任意的(分、时、日、月、周)时间都执行
#-表示一个时间范围段,如5-7点
#,表示分隔时段,如6,0,4表示周六、日、四
#/1表示每隔n单位时间,如*/10每10分钟

2.2计划任务编写范例

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月的周天的凌晨两点执行
*/10 02 * * * ls #每天两点每隔十分钟执行一次 200 -250
* * * * *  ls #每分钟都执行
00 00 14 2 * ls# 每年2月14日的凌晨执行命令
*/5 * * * * ls #每隔五分钟执行一次
00 02 * 158 * ls #1,5,8月的每天凌晨2点执行
00 02 1-8 * * ls #每月的1-8号凌晨2点执行
00 21 * * * ls #每天晚上21点执行
45 4 1,10,22 * * ls #每月的1,10,22的凌晨4点45执行
45 4 1-10 * * ls #每月的1-10号的凌晨4点45执行
3,15 8-11 */2 * * ls #每隔两天的早上8-11点的每3,15分钟执行
00 23-7/1 * * * ls #每天的前天23点到次日凌晨7点每隔一小时执行一次
15 21 * * 1-5 ls #周一到周五的晚上21点15执行

2.3使用crond实现计划任务

参数 定义
-e 编辑定时任务
-l 查看定时任务
-r 删除定时任务(清空>)
-u 指定其他用户

 

 

 

2.3.1定时时间同步

使用root用户每5分钟执行一次时间同步

 

#1.如何同步时间
[root@localhost ~]# ntpdate time.windows.com &> /dev/null
#2.配置定时任务
[root@localhost ~]# crontab -e -u root
[root@localhost ~]# crontab -l  -u root
*/5 * * * * ntpdate time.windows.com &> /dev/null

 

2.3.2每半小时sync

每天的下午3,5点,每隔半小时执行一次sync命令

 

[root@localhost ~]# crontab -l
*/5 * * * * ntpdate time.windows.com &> /dev/null
*/30 15,17 * * * sync &> /dev/null

 

2.3.3每天备份文件

脚本如下:
#!/bin/bash
backup_dir=/root/back
Date=$(date +%F)
Hostname=$(hostname)
if [ !  -d ${backup_dir} ];then
 mkdir -p  ${backup_dir}
fi
cd / 
tar -czf ${backup_dir}/${Date}_${Hostname}_etc.tar.gz  etc
定时任务如下
[root@localhost ~]# crontab -l
00 03 * * * bash /root/backup.sh &>/dev/null

2.4拒绝特定用户使用

crond如何拒绝某个用户使用

1.使用root将需要拒绝的用户加入/etc/cron.deny

 

[root@localhost ~]#  echo "yang" >> /etc/cron.deny

 

 2.登陆该普通用户,测试是否能编写定时任务

 

[yang@localhost~]$crontab -e
You(yang) are not allowed to use this program(crontab)
Seecrontab(1)formoreinformation

 

posted @ 2021-07-23 20:22  西红柿要上天  阅读(141)  评论(0编辑  收藏  举报