How to kill time.Sleep(time.Until(nextExecute)) ?
That is an old sessions cleanup task, that needs to execute every minute as background task. Works fine but after SIGINT all program still waits time.Sleep... Any cnow how to kill time.Sleep or alternate routine code?
func SessionCleanupTask() {
var quit = make(chan os.Signal)
signal.Notify(quit, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) // kbdloss,ctrl+c,terminate,quit
for {
select {
case <- quit:
return
default:
nextExecute := time.Now().Add(time.Minute)
time.Sleep(time.Until(nextExecute))
log.Println("peek: SessionCleanupTask")
}
}
}
func init() {
go SessionCleanupTask()
}
You cannot interrupt time.Sleep. Use time.After in the select statement instead of the default case.
Also, you have to buffer the os.Signal channel or you are going to miss the signal if it arrives while "SessionCleanupTask" executes; Notify doesn't wait for a receiver:
Package signal will not block sending to c: the caller must ensure that c has sufficient buffer space to keep up with the expected signal rate. For a channel used for notification of just one signal value, a buffer of size 1 is sufficient.
quit := make(chan os.Signal, 1) // buffered
signal.Notify(quit, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
for {
select {
case <-quit:
return
case <-time.After(time.Minute):
log.Println("peek: SessionCleanupTask")
}
}