是否可以每50小时执行一次cronjob? [英] Is it possible to execute cronjob in every 50 hours?
问题描述
我一直在寻找一个cron时间表,该时间表每50小时执行一次脚本。使用cron可以轻松地每两天运行一次作业。我们可以表示为
I've been looking for a cron schedule that executes a script for every 50 hours. Running a job for each 2 days is simple with cron. We can represent like
0 0 */2 * * command
但是每50小时呢?
推荐答案
如果要每 n
小时运行一次cron,其中 n
不会除以24,因此您不能使用cron做到这一点是可能的。为此,您需要在测试中检查时间的cron中进行测试。最好查看UNIX时间戳,这是 1970-01-01 00:00:00 UTC
以来的总秒数。假设我们要从McFly到达Riverdale的那一刻开始:
If you want to run a cron every n
hours, where n
does not divide 24, you cannot do this cleanly with cron but it is possible. To do this you need to put a test in the cron where the test checks the time. This is best done when looking at the UNIX timestamp, the total seconds since 1970-01-01 00:00:00 UTC
. Let's say we want to start from the moment McFly arrived in Riverdale:
% date -d '2015-10-21 07:28:00' +%s
1445412480
对于cronjob,每运行<$ c在2015年10月21日07:28:00之后的$ c> 50 小时,crontab如下所示:
For a cronjob to run every 50
th hour after `2015-10-21 07:28:00', the crontab would look like this:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
28 * * * * hourtestcmd "2015-10-21 07:28:00" 50 && command
,其中 hourtestcmd
定义为
#!/usr/bin/env bash
starttime=$(date -d "$1" "+%s")
# return UTC time
now=$(date "+%s")
# get the amount of hours
hours=$(( (now - starttime) / 3600 ))
# get the amount of remaining minutes
minutes=$(( (now - starttime - hours*3600) / 60 ))
# set the modulo
modulo=$2
# do the test
(( now >= starttime )) && (( hours % modulo == 0 )) && (( minutes == 0 ))
备注:给出了UNIX时间在UTC。如果您的cron在受夏时制时间影响的其他时区中运行,则可能导致程序偏移执行,或者当夏时制生效时,增量为51小时或49小时。
Remark: UNIX time is given in UTC. If your cron runs in a different time-zone which is influenced by daylight saving time, it could lead to programs being executed with an offset or when daylight saving time becomes active, a delta of 51hours or 49hours.
注释: UNIX时间不受leap秒的影响
Remark: UNIX time is not influenced by leap seconds
注释: cron
没有亚秒精度
备注:请注意我如何将分钟数保持一致到开始时间的那一个这样可以确保cron仅每小时运行一次。
Remark: Note how I put the minutes identical to the one in the start time. This to make sure the cron only runs every hour.
这篇关于是否可以每50小时执行一次cronjob?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!