Sleep until a specific time/date

Viewed 113179

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"-daemon is not a solution, as I need to block a running script until a certain date/time.

Is there such a command?

21 Answers

As mentioned by Outlaw Programmer, I think the solution is just to sleep for the correct number of seconds.

To do this in bash, do the following:

current_epoch=$(date +%s)
target_epoch=$(date -d '01/01/2010 12:00' +%s)

sleep_seconds=$(( $target_epoch - $current_epoch ))

sleep $sleep_seconds

To add precision down to nanoseconds (effectively more around milliseconds) use e.g. this syntax:

current_epoch=$(date +%s.%N)
target_epoch=$(date -d "20:25:00.12345" +%s.%N)

sleep_seconds=$(echo "$target_epoch - $current_epoch"|bc)

sleep $sleep_seconds

Note that macOS / OS X does not support precision below seconds, you would need to use coreutils from brew instead → see these instructions

Use sleep, but compute the time using date. You'll want to use date -d for this. For example, let's say you wanted to wait until next week:

expr `date -d "next week" +%s` - `date -d "now" +%s`

Just substitute "next week" with whatever date you'd like to wait for, then assign this expression to a value, and sleep for that many seconds:

startTime=$(date +%s)
endTime=$(date -d "next week" +%s)
timeToWait=$(($endTime- $startTime))
sleep $timeToWait

All done!

You can stop a process from executing, by sending it a SIGSTOP signal, and then get it to resume executing by sending it a SIGCONT signal.

So you could stop your script by sending is a SIGSTOP:

kill -SIGSTOP <pid>

And then use the at deamon to wake it up by sending it a SIGCONT in the same way.

Presumably, your script will inform at of when it wanted to be woken up before putting itself to sleep.

I wanted an script that only checked the hours and minutes so I could run the script with the same parameters every day. I don't want to worry about which day will be tomorrow. So I used a different approach.

target="$1.$2"
cur=$(date '+%H.%M')
while test $target != $cur; do
    sleep 59
    cur=$(date '+%H.%M')
done

the parameters to the script are the hours and minutes, so I can write something like:

til 7 45 && mplayer song.ogg

(til is the name of the script)

no more days late at work cause you mistyped the day. cheers!

To follow on SpoonMeiser's answer, here's a specific example:

$cat ./reviveself

#!/bin/bash

# save my process ID
rspid=$$

# schedule my own resuscitation
# /bin/sh seems to dislike the SIGCONT form, so I use CONT
# at can accept specific dates and times as well as relative ones
# you can even do something like "at thursday" which would occur on a 
# multiple of 24 hours rather than the beginning of the day
echo "kill -CONT $rspid"|at now + 2 minutes

# knock myself unconscious
# bash is happy with symbolic signals
kill -SIGSTOP $rspid

# do something to prove I'm alive
date>>reviveself.out
$

timeToWait = $(( $end - $start ))

Beware that "timeToWait" could be a negative number! (for example, if you specify to sleep until "15:57" and now it's "15:58"). So you have to check it to avoid strange message errors:

#!/bin/bash
set -o nounset

### // Sleep until some date/time. 
# // Example: sleepuntil 15:57; kdialog --msgbox "Backup needs to be done."


error() {
  echo "$@" >&2
  exit 1;
}

NAME_PROGRAM=$(basename "$0")

if [[ $# != 1 ]]; then
     error "ERROR: program \"$NAME_PROGRAM\" needs 1 parameter and it has received: $#." 
fi


current=$(date +%s.%N)
target=$(date -d "$1" +%s.%N)

seconds=$(echo "scale=9; $target - $current" | bc)

signchar=${seconds:0:1}
if [ "$signchar" = "-" ]; then
     error "You need to specify in a different way the moment in which this program has to finish, probably indicating the day and the hour like in this example: $NAME_PROGRAM \"2009/12/30 10:57\"."
fi

sleep "$seconds"

# // End of file

I actually wrote https://tamentis.com/projects/sleepuntil/ for this exact purpose. It's a bit over-kill most of the code comes from BSD 'at' so it's fairly standard-compliant:

$ sleepuntil noon && sendmail something

You can calculate the number of seconds between now and the wake-up time and use the existing 'sleep' command.

You could perhaps use 'at' to send a signal to your script, which sat waiting for that signal.

To extend the main answer, here is some valid examples regarding the date string manipulation:

sleep $(($(date -f - +%s- <<< $'+3 seconds\nnow')0)) && ls

sleep $(($(date -f - +%s- <<< $'3 seconds\nnow')0)) && ls

sleep $(($(date -f - +%s- <<< $'3 second\nnow')0)) && ls

sleep $(($(date -f - +%s- <<< $'+2 minute\nnow')0)) && ls

sleep $(($(date -f - +%s- <<< $'tomorrow\nnow')0)) && ls

sleep $(($(date -f - +%s- <<< $'tomorrow 21:30\nnow')0)) && ls

sleep $(($(date -f - +%s- <<< $'3 weeks\nnow')0)) && ls

sleep $(($(date -f - +%s- <<< $'3 week\nnow')0)) && ls

sleep $(($(date -f - +%s- <<< $'next Friday 09:00\nnow')0)) && ls

sleep $(($(date -f - +%s- <<< $'2027-01-01 00:00:01 UTC +5 hours\nnow')0)) && ls

Consider also this concise Bash one-liner:

sleep $((`date -d "22:00" +%s`-`date  +%s`))

This is a Bash v4.4.20(1) arithmetic expression, consisting of two date command substitutions. The first date command outputs your target until time in seconds (since 1970) and the latter the respective current time. These two numbers are separated by a minus sign for the arithmetic. As a result, you get seconds as a parameter for the sleep command.

There's a nice little Rust CLI tool yawn that does the job. If you have Rust installed already then this might be an easy option (cargo install yawn). Otherwise, Apple and Linux executables are available on Github.

This script will wait until 4 of July, 21:44:59

while (( $(date +"%Y%m%d%H%M%S") < 20220704214459 )); do :; done
echo "It is time!"

Use tarry. It's a tool I wrote to specifically do this.

https://github.com/metaphyze/tarry/

This is a simple command line tool for waiting until a specific time. This is not the same as "sleep" which will wait for a duration of time. This is useful if you want to execute something at a specific time or more likely execute several things at exactly the same time such as testing if a server can handle multiple very simultaneous requests. You could use it like this with "&&" on Linux, Mac, or Windows:

   tarry -until=16:03:04 && someOtherCommand

This would wait until 4:03:04 PM and then execute someOtherCommand. Here's a Linux/Mac example of how to run multiple requests all scheduled to start at the same time:

   for request in 1 2 3 4 5 6 7 8 9 10
   do
       tarry -until=16:03:04 && date > results.$request &
   done

Ubuntu, Linux, and Windows binaries are available through links on the page.

Related