crontab小技巧

有一些机器因为应用软件不稳定,需要定期重启,计划每月重启一次。
为防止影响业务运行,设置在周日凌晨3点重启,这个时间段对业务的影响最小,同时也避开了备份、维护等夜间工作。
开始的时候想着很简单,在crontab里这样加一条就好了:

0 3 1-7 * 7 /sbin/reboot
就是说每个月1到7号,如果是周日,就在3点重启一下。
结果发现这个脚本每到周日必定重启,不管是不是1-7号。
man 5 crontab 看下帮助
Note: The day of a command's execution can be specified by two fields — day of month, and day of week.  If both fields are restricted (i.e., aren't *), the command  will be run when either field matches the current time.  For example,``30  4 1,15 * 5'' would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday. One can, however, achieve the desired result by adding a test to the command (see the last example in EXAMPLE CRON FILE below).

原来crontab里如果设置日期,每月日期和每周日期这两个同时会起作用,也就是说上面那个设置实际上1号到7号以及每个周日都会重启,这个明显并不符合我们的需要。
只能把这个写的复杂一些了,设置crontab如下:

0 3 1-7 * * test "$(date +%u)" = "7" && /sbin/reboot

也就是说1号到7号每天会检查一下,用test测试一下,如果是周日,就重启。
结果下个月发现没有重启,脚本失效了。
又是试验了好些方法,发现crontab里不可以用 && 连接两个命令
那就只能写个外部脚本啦

echo 'test "$(date +%u)" = "7" && /sbin/reboot' >/usr/local/bin/reboot7.sh
chmod +x /usr/local/bin/reboot7.sh
crontab -e 增加一条
0 3 1-7 * * /usr/local/bin/reboot7.sh

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值