问题描述
我一直在寻找每 50 小时执行一次脚本的 cron 计划.使用 cron 每 2 天运行一次作业很简单.我们可以表示像
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 小时呢?
But what about every 50 hours?
推荐答案
如果你想每 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
对于在2015-10-21 07:28:00"之后每 50
小时运行的 cronjob,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 时间不受闰秒的影响
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屋!
更多推荐
[db:关键词]
发布评论