du127953 2018-10-11 03:02
浏览 33
已采纳

Golang例行程序

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()
}
  • 写回答

1条回答 默认 最新

  • dongyu1983 2018-10-11 03:23
    关注

    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")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源