osnosn

  博客园 :: 首页 :: 博问 :: 闪存 :: :: 联系 :: 订阅 订阅 :: 管理 ::

Openwrt_Linux_crontab任务_顺序执行脚本

转载注明来源: 本文链接 来自osnosn的博客,写于 2020-12-21.

Linux (openwrt,debian,centos...) 中 crontab 的任务太多,不想挤在一起同时执行

  • 可以考虑放到一个shell脚本中顺序执行。这样,机器的负荷就不会在那些特定的时间点暴增。
    crontab 中 只需要加入一行*/5 * * * * /path.../runTaskInSequence.sh,每5分钟执行一次即可。
  • 设置了定时任务后。
    OpenWRT 中 systemlog中会出现很多 cron.err crond[...]: USER ... pid ... cmd ...的信息。
    只能把 cron的日志(cronloglevel)输出级别改为 9 才不会输出。改 conloglevel 没用。
    • 修改 /etc/config/system文件中,system -> 改option cronloglevel '9'
      或者用 uci 命令修改,uci set system.@system[0].cronloglevel='9'; uci commit system
      或者在 web luci上,system -> system -> Logging -> Cron Log Level 改为 "Warning"。
    • 然后 重启 crond 服务。才能生效
      /etc/init.d/crond restart 或者在 web luci上,system -> Startup 中找到 crond,点击"重启"。
  • 以下脚本用 sh, dash, bash 都行
#!/bin/sh
# filename: runTaskInSequence.sh

# current dir
MYTK=$(dirname $(readlink -f -- $0))
cd $MYTK

MIN="$(date '+%M')"     #min
MIN="${MIN#0}"          #去掉首位的0
MIN2="$(($MIN/10))"     # 取十位
#MIN1="$(($MIN%10))"     # 取个位
#HOUR="$(date '+%H')"    #hour
#HOUR="${HOUR#0}"        #去掉首位的0
#WEEK="$(date '+%u')"    #day of week (1..7); 1 is Monday

## run every hour
if [ "$MIN" -eq 10 ]; then
   true  #如果下面两行都注释掉,脚本不会出错
   ./mytask11.sh
   ./mytask12.sh
fi

## run every half hour
if [ "$MIN" -eq 10 -o "$MIN" -eq 40 ]; then
   ./mytask21.sh
   ./mytask22.sh
fi

## run */10 min
if [ "$MIN1" -eq 0 ]; then
   ./mytask31.sh
   ./mytask32.sh
fi

## run */5 min
./mytask01.sh
  • 如果你的shell不支持 "%" 运算, 可以用下面这个, 调用外部命令 expr 来计算
#!/bin/bash

#当前目录
MYTK=$(/usr/bin/dirname $(/bin/readlink -f -- $0))
cd $MYTK

MIN="$(date '+%M')"       # 获取当前分钟数
MIN="${MIN#0}"            #去掉首位的0
MIN2="$(expr $MIN / 10)"  #min/10
#MIN1="$(expr $MIN % 10)"  #min%10
#HOUR="$(date '+%H')"      # 获取当前小时数
#HOUR="${HOUR#0}"          #去掉首位的0
...

---end---


转载注明来源: 本文链接 https://www.cnblogs.com/osnosn/p/14168336.html 来自osnosn的博客.

posted on 2020-12-21 16:09  osnosn  阅读(1175)  评论(0编辑  收藏  举报