Is it possible to execute cronjob in every 50 hours?

前端 未结 1 693
青春惊慌失措
青春惊慌失措 2020-12-12 00:19

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          


        
相关标签:
1条回答
  • 2020-12-12 01:22

    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.

    0 讨论(0)
提交回复
热议问题