Skip to content

Instantly share code, notes, and snippets.

@jsleeio
Created January 23, 2020 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsleeio/b525c6dd8156575909ff940d86bbc5f9 to your computer and use it in GitHub Desktop.
Save jsleeio/b525c6dd8156575909ff940d86bbc5f9 to your computer and use it in GitHub Desktop.
sleep until a quantized time, implemented in both Bourne shell and Go
package main
import (
"flag"
"fmt"
"time"
)
func main() {
multiple := flag.Duration("multiple", 5*time.Minute, "sleep until the next integer multiple of this time")
sleepchunk := flag.Duration("sleep-chunk", 5*time.Second, "sleep in blocks of up to this much")
flag.Parse()
now := time.Now()
nextmultiple := now.Truncate(*multiple).Add(*multiple)
fmt.Printf("target time is %v\n", nextmultiple)
for {
remaining := time.Until(nextmultiple)
if remaining < 0 {
break
}
fmt.Printf("time now is %v, time left to sleep is %v\n", time.Now(), remaining)
if remaining < *sleepchunk {
time.Sleep(remaining)
} else {
time.Sleep(*sleepchunk)
}
}
fmt.Printf("time now is %v\n", time.Now())
}
#!/bin/sh
# quantizing amount, in seconds
chunk=300
# maximum sleep time
incr=15
while getopts "c:i:" opt ; do
case "$opt" in
c) chunk="$OPTARG" ;;
i) incr="$OPTARG" ;;
*) echo "usage: quantized-sleep.sh [-c CHUNKSECONDS] [-i INCREMENTSECONDS]" >&2; exit 1 ;;
esac
done
# date math
now=$(date +%s)
last=$((now - now % chunk))
next=$((last + chunk))
while true ; do
now=$(date +%s)
sleep=$((next-now))
echo "last=$last, now=$(date +%s), next=$next, remaining=$sleep"
if [ "$sleep" -ge "$incr" ] ; then
sleep "$incr"
else
sleep "$sleep"
break
fi
done
date
$ ./quantized-sleep.sh -c 30 -i 15
last=1579786080, now=1579786095, next=1579786110, remaining=15
last=1579786080, now=1579786110, next=1579786110, remaining=0
Fri 24 Jan 2020 00:28:30 AEDT
$ ./quantized-sleep.sh -c 30 -i 5
last=1579786260, now=1579786262, next=1579786290, remaining=28
last=1579786260, now=1579786267, next=1579786290, remaining=23
last=1579786260, now=1579786272, next=1579786290, remaining=18
last=1579786260, now=1579786277, next=1579786290, remaining=13
last=1579786260, now=1579786282, next=1579786290, remaining=8
last=1579786260, now=1579786287, next=1579786290, remaining=3
Fri 24 Jan 2020 00:31:30 AEDT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment