Answers:
crontab文件仅允许您指定:
minute (0-59)
hour (0-23)
day of the month (1-31)
month of the year (1-12)
day of the week (0-6 with 0=Sunday)
因此,无法指定应使用的周数。
编写包装脚本可能是最好的选择。
您可以使用以下命令在shell脚本中获取星期数
date +%U
要么
date +%V
取决于您是否希望周日从星期日或星期一开始。
所以你可以使用
week=$(date +%V)
check=$(( ($week - 1) % 3 ))
并且$ check在一年的第1、4、7,...周将为0。
如果您可以在两次运行之间保存一个时间戳文件,则可以检查它的日期,而不是仅仅依靠当前日期。
如果您的find命令支持-mtime
(或具有-mmin
)小数值(GNU find具有两个值,POSIX似乎都不需要),则可以通过find和touch来“限制” cron作业。
或者,如果您有一个stat命令支持将文件日期显示为“距纪元以来的秒数”(例如,来自Gnu coreutils的stat以及其他实现),则可以使用date,stat和shell的比较运算符(以及用触摸到更新的时间戳文件)。如果它可以进行格式化,那么您也可以使用ls代替stat(例如,来自GNU fileutils的ls)。
下面是一个Perl程序(我称它为n-hours-ago
),如果原始时间戳足够旧,它将更新时间戳文件并成功退出。它的用法文本显示了如何在crontab条目中使用它来限制cron作业。它还描述了“夏令时”的调整以及如何处理以前运行的“迟到”时间戳。
#!/usr/bin/perl
use warnings;
use strict;
sub usage {
printf STDERR <<EOU, $0;
usage: %s <hours> <file>
If entry at pathname <file> was modified at least <hours> hours
ago, update its modification time and exit with an exit code of
0. Otherwise exit with a non-zero exit code.
This command can be used to throttle crontab entries to periods
that are not directly supported by cron.
34 2 * * * /path/to/n-hours-ago 502.9 /path/to/timestamp && command
If the period between checks is more than one "day", you might
want to decrease your <hours> by 1 to account for short "days"
due "daylight savings". As long as you only attempt to run it at
most once an hour the adjustment will not affect your schedule.
If there is a chance that the last successful run might have
been launched later "than usual" (maybe due to high system
load), you might want to decrease your <hours> a bit more.
Subtract 0.1 to account for up to 6m delay. Subtract 0.02 to
account for up to 1m12s delay. If you want "every other day" you
might use <hours> of 47.9 or 47.98 instead of 48.
You will want to combine the two reductions to accomodate the
situation where the previous successful run was delayed a bit,
it occured before a "jump forward" event, and the current date
is after the "jump forward" event.
EOU
}
if (@ARGV != 2) { usage; die "incorrect number of arguments" }
my $hours = shift;
my $file = shift;
if (-e $file) {
exit 1 if ((-M $file) * 24 < $hours);
} else {
open my $fh, '>', $file or die "unable to create $file";
close $fh;
}
utime undef, undef, $file or die "unable to update timestamp of $file";
exit 0;