Skip to content

Instantly share code, notes, and snippets.

@mowings
Last active February 4, 2024 22:28
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mowings/a32fbf4dd46d9fb9661822056ceda91c to your computer and use it in GitHub Desktop.
Save mowings/a32fbf4dd46d9fb9661822056ceda91c to your computer and use it in GitHub Desktop.
Bash -- sleep until a specific time, like tomorrow midnight
#!/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
@brandonros
Copy link

Could you do this but with a "run every minute" example (which is slightly different than run in a loop and sleep 60 seconds?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment