Cron作业运行每月的第一个或最后一个选定的星期几 [英] Cron job to run every first or last chosen day of week of every month

查看:1125
本文介绍了Cron作业运行每月的第一个或最后一个选定的星期几的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,用户选择何时运行脚本。我有字段{time,week of day,first / last} 。现在当用户选择例如:10:45 AM每个第一个星期一 - 这意味着在每个月的第一个星期一运行脚本,我该如何转换为cron作业。

I have a form where user chooses when to run a script. I've fields {time,day of week, first/last}. Now when the user chooses for example: 10:45 AM every first Monday - Which means run script on every first Monday of every month, how can I convert this to cron job.

谢谢。

推荐答案

不幸的是,crontab条目中的日期和星期字段是ORed一起,而不是与。所以你不能真正做一个第一个星期一的月与crontab领域单独;你需要额外的逻辑。你可以这样做:

Unfortunately, the day-of-month and day-of-week fields in a crontab entry are ORed together rather than ANDed. So you can't really do a "first Monday of the month" with crontab fields alone; you need additional logic. You could do something like this:

min hr 1-7 * * [ `date +%w` -eq 1 ] && first-monday.sh

查找工作日的最后一个实例有点棘手,因为它取决于很多天是在这个月:

Finding the last instance of a weekday is a bit trickier since it depends on how many days are in the month:

min hr 25-31 1,3,5,7,8,10,12 * [ `date +%w` -eq 5 ] && last-friday.sh
min hr 24-30 4,6,9,11        * [ `date +%w` -eq 5 ] && last-friday.sh
min hr 22-28 2               * [ `date +%w` -eq 5 ] && last-friday.sh

在闰年,2月29日星期五,运行脚本在22nd,而不是因为cron作业不能指定一年,这是尽可能接近你可以得到。

On leap years in which February 29th falls on Friday, that last entry will actually run the script on the 22nd instead, but since cron jobs can't specify a year, that's about as close as you can get.

这篇关于Cron作业运行每月的第一个或最后一个选定的星期几的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆