Crontab >> Linux定时执行任务 >> Run at random interval 在随机的间隔下运行

制定定时执行计划

Crontab >>Linux定时执行任务

安装: yum -y install crontab

# 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

操作符:【 * 】 代表所有范围,eg: * * * * *  每分钟执行一次,不管是几点,几小时,几天,几月,星期几。

              【 , 】代表个别的点,eg: 30 9,18 * * * 每天的9:30, 18:30执行一次。

              【 - 】代表自定义的连续区间 eg: 30 9-18 * * *  每天的9点到18点,中间每个小时的第30分钟,就执行。

              【 / 】代表每隔多少时间 eg: 30 */3 * * * 每天从 0点开始,每隔三个小时执行一次

添加定时任务: crontab -e ,然后按 i 进入编辑模式

注意:最好在文本开头写上 #!/bin/bash 表示可以执行bash脚本,再附上PATH变量,【env】命令可以查询到。

 

Although cron requires that each entry in a crontab end in a newline character, neither the crontab command nor the cron daemon will detect this error. Instead, the crontab will appear to load normally. However, the command will never run. The best choice is to ensure that your crontab has a blank line at the end. 

                                                                                                                                                                                                                                                                                    - -man 4 crontabs

大意如下:crontab的定时任务之间无符号分割,还是正常加载,日志也会打印,不报错,但是command不执行。

每条定时命令要用空白行隔开,否则可能出现查询日志 cat /var/log/cron 有执行显示,但实际命令未执行。

 更多未执行情况可查阅 >> https://github.com/tony-yin/Why-Cronjob-Not-Work

refer:

本文标题:为什么 crontab 不执行

文章作者:Tony

原始链接:https://tony-yin.github.io/2018/10/29/Why-Crontab-Not-Work/

 

查看定时任务: crontab -l

查看执行日志: cat /var/log/cron 

输出执行情况:

 

> 重定向输出(覆盖)
>> 追加
2 StandError标准错误
1 StandOutput标准输出
& 2 or 1 的标识符,不加的话,会把 > 之后看作文件名
>/dev/null 2>&1 把日志的执行情况输出到空目录

 2>&1 标准错误重定向到标准输出

Centos7 开启cron服务:systemctl start crond;查询cron状态:systemctl status crond

 

编写.sh文件tips:

:set ff查看编码格式,dos格式可能不会被执行。

:set ff=unix 改变编码格式。

chmod +x filename 赋予.sh文件 执行权限。

 

执行.py文件tips:

>覆盖输出

>>追加输出

python .py > result.txt 将.py文件的执行结果覆盖输出到result.txt文件中,追加输出 >> 。

添加随机间隔

需求缘由,老大反应 cron * * * * * 每分钟向服务器发送请求,具体到秒:12:00:01,12:01:01,12:02:01 execute command,另外 * * * * * 每分钟的定时任务也很多,其他定时任务具体执行时间也会有一个”最大公约数“,就引发了一个问题, 【同一时间】过多请求,服务器压力过大,提出能不能在【一定时间随机】发送请求。思路如下:cron 定时计划不变,在之后的execute command 中改变,让具体的.sh文件延时运行,延时的刻度随机。

logfile=crontab-demo.logt0to60secs="RANDOM % 60" # 在60中取一个随机数

* * * * * r=$(($t0to180secs)) ; sleep ${r}s ; bash xxx.sh >> $logfile 2>&1  # 将随机数赋给一个变量,然后执行sleep函数,暂停一段时间,之后再执行 .sh 文件 


Refer:
https://github.com/taw00/howto/blob/master/howto-schedule-cron-jobs-to-run-at-random-intervals.md

Title:
HowTo Schedule Cron Jobs to Run at Random Intervals
Author:
taw00



 

posted @ 2020-03-02 23:28  walk_the_talk  Views(693)  Comments(0)    收藏  举报