Last active
April 6, 2025 17:30
-
-
Save mowings/a32fbf4dd46d9fb9661822056ceda91c to your computer and use it in GitHub Desktop.
Bash -- sleep until a specific time, like tomorrow midnight
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Sometimes you want to sleep until a specific time in a bash script. This is useful, for instance | |
# in a docker container that does a single thing at a specific time on a regular interval, but does not want to be bothered | |
# with cron or at. The -d option to date is VERY flexible for relative times. | |
# See | |
# https://www.gnu.org/software/coreutils/manual/html_node/Relative-items-in-date-strings.html#Relative-items-in-date-strings | |
# For details | |
# ALPINE USERS: You will need to install coreutils, as the built-in busybox date does not handle -d correctly. | |
# This script runs in an infinite loop, waking up every morning at 3:00AM | |
WAKEUP="03:00" # Wake up at this time tomorrow and run a command | |
while : | |
do | |
SECS=$(expr `date -d "tomorrow $WAKEUP" +%s` - `date -d "now" +%s`) | |
echo "`date +"%Y-%m-%d %T"`| Will sleep for $SECS seconds." | |
sleep $SECS & # We sleep in the background to make the screipt interruptible via SIGTERM when running in docker | |
wait $! | |
echo "`date +"%Y-%m-%d %T"`| Waking up" | |
# Run your command here | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you do this but with a "run every minute" example (which is slightly different than run in a loop and sleep 60 seconds?)