Skip to content

Instantly share code, notes, and snippets.

@sineemore
Created July 28, 2021 13:41
Show Gist options
  • Save sineemore/8628c32f6fad3152ebd8227aed904a29 to your computer and use it in GitHub Desktop.
Save sineemore/8628c32f6fad3152ebd8227aed904a29 to your computer and use it in GitHub Desktop.
sleep less on Ctrl+C
package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
if len(os.Args) != 2 {
fmt.Println("Specify time to sleep")
os.Exit(1)
}
duration, err := time.ParseDuration(os.Args[1])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
end := time.Now().Add(duration)
timer := time.NewTimer(duration)
for {
fmt.Printf("sleeping %s seconds\n", duration)
select {
case <-timer.C:
fmt.Println("done")
return
case <-signals:
if !timer.Stop() {
<-timer.C
}
fmt.Println("half duration")
duration = time.Until(end) / 2
end = time.Now().Add(duration)
timer = time.NewTimer(duration)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment