Created
July 28, 2021 13:41
-
-
Save sineemore/8628c32f6fad3152ebd8227aed904a29 to your computer and use it in GitHub Desktop.
sleep less on Ctrl+C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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