Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

cron - Is it possible to execute cronjob in every 50 hours?

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

But what about every 50 hours?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

For a cronjob to run every 50th 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

with hourtestcmd defined as

#!/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 ))

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.

Remark: UNIX time is not influenced by leap seconds

Remark: cron has no sub-second accuracy

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...