Friday, July 11, 2008

How to sleep until an hour has elapsed.

Let say you want to run a script and then run another one an hour after the current one started
# in the first script
# save the current time

awk 'BEGIN { srand(); printf("%d\n", srand()+3610)}' > /tmp/start_time
 

# in the second script
# sleep until the rest of the hour has passed.

ONE_HOUR_LATER=$(cat /tmp/lstart_time)
SLEEP_TIME=$(awk -v ohl=$ONE_HOUR_LATER 'BEGIN { srand(); printf("%d\n", ohl-srand())}')
sleep $SLEEP_TIME
 

The trick is that srand will return the seconds since the epoch on it's first call. Yes it's in the man page, but on solaris it seems to be the second call. Beware!

No comments: