Crontab 每两周执行一次

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:25   1890   0

Crontab 每两周执行一次 - - 香港硅谷

Crontab 每两周执行一次

作者: Tsung Hao
13-Apr-09
Linux
浏览次数: 1826
| 评论 ↓

Tweet

今天被问到一个问题: Crontab 如何设定两周执行一次.

问题假设: 每个月 "第 1, 3 周" 的 "星期一 早上6点" 要执行 "ls /tmp" 的指令.

原本想想应该是直接设定 "0 6 1-7,15-21 * 1" 就可以了, 结果 1-7, 15-21 和 星期一也都会跑.

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.
注: weekday 和 day 这两栏很容易造成混淆, 假如两栏同时都被指定时, 只需满足其中一栏就算符合.

目前想到的解法, 就是在程式判断, 不然就是在 Crontab 设定时判断, 找了很多资料, 还没找到正确解法. (若有知道解法的, 请不吝指教.. Orz.)
解法

Crontab 中设定: "0 6 1-7,15-21 * * if [ `date '+\%w'` = "1" ]; then ls /tmp;fi"
注1: bash 里面直接用 "if [ `date '+%w'` = "1" ]; then ls /tmp;fi" 即可, 但是在 Crontab 中, "%" 是特殊字符, 要加上跳脱字符(escape character).
注2: "date '+%w'" => 用数字显示星期几 (0~6 = 星期天~ 星期六)
注3: "ls /tmp" 换成想要执行的指令即可.

相关解法

找到解法看起来比较像, 但是看不懂是怎么设定的: Crontab Setting Ineffective
上述采用这类的解法: biweekly schedule through cron - dBforums

相关网页

Cron 详细写法: Crontab 的写法(@reboot, @yearly...)
posted on 2012-12-03 13:48 lexus 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lexus/archive/2012/12/03/2799497.html

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP