Golang例程每分钟任务

Golang routines every minute task

如何杀死 time.Sleep(time.Until(nextExecute)) ?

这是一个旧的会话清理任务,需要作为后台任务每分钟执行一次。工作正常,但在 SIGINT 之后所有程序仍在等待 time.Sleep...知道如何终止 time.Sleep 或替代例程代码吗?

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()
}

你不能打扰time.Sleep。在 select 语句中使用 time.After 而不是默认大小写。

此外,您必须缓冲 os.Signal 通道,否则如果信号在 "SessionCleanupTask" 执行时到达,您将错过信号;通知不等待接收者:

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")
    }
}