Sleep until a specific time/date

前端 未结 18 2095
栀梦
栀梦 2020-11-28 21:13

I want my bash script to sleep until a specific time. So, I want a command like \"sleep\" which takes no interval but an end time and sleeps until then.

The \"at\"-d

18条回答
  •  迷失自我
    2020-11-28 21:36

    On OpenBSD, the following could be used to compact a */5 5-minute crontab(5) job into an 00 hourly one (to make sure fewer emails are generated, all whilst performing the same task at exact intervals):

    #!/bin/sh -x
    for k in $(jot 12 00 55)
      do
      echo $(date) doing stuff
      sleep $(expr $(date -j +%s $(printf %02d $(expr $k + 5))) - $(date -j +%s))
    done
    

    Note that the date(1) would also break the sleep(1) by design on the final iteration, as 60 minutes is not a valid time (unless it is!), thus we won't have to wait any extra time prior to getting our email report.

    Also note that should one of the iterations take more than 5 minutes allotted to it, the sleep would likewise graciously fail by design by not sleeping at all (due to what is a negative number interpreted as a command-line option, instead of wrapping around to the next hour or even eternity), thus making sure your job could still complete within the hour allotted (e.g., if only one of the iterations takes a little bit more than 5 minutes, then we would still have the time to catch up, without anything wrapping around to the next hour).

    The printf(1) is needed because date expects exactly two digits for the minute specification.

提交回复
热议问题