dpy83214 2014-08-02 01:22
浏览 34

Golang的股票代号和守护程序

Is it possible to use Ticker to implemented the graceful termination of a long running daemon process? I read the other related thread on here that you should always close the channel to avoid memory leak, but if I run this in a daemon mode (let said I use daemonize to handle the daemon operation outside of golang), and there's really no way for it to do any collective cleanup before the process is terminated. Unless I'm missing something, I'm here to ask whether there's an alternative/better to do this in Golang

func main() {
  ticker := time.NewTicker(Interval)
  workers := make(chan bool, 1)

  for t := range ticker.C {
    select {
      case <- ticker.C:
        log.Println("Scheduled task is triggered.", t)
        go runWorker(workers)
      case <- workers:
        log.Println("Scheduled task is completed.")
        // can't return, it needs to be continue running
    }
  }
}
  • 写回答

2条回答 默认 最新

  • dsfdgdsfd23212 2014-08-02 02:44
    关注

    I'm not sure I fully understand your goal, however you could always use signal.Notify:

    func main() {
        ticker := time.NewTicker(Interval)
        workers := make(chan bool, 1)
        death := make(chan os.Signal, 1)
        signal.Notify(death, os.Interrupt, os.Kill)
    
        for {
            select {
            case <-ticker.C:
                log.Println("Scheduled task is triggered.", t)
                go runWorker(workers)
            case <-workers:
                log.Println("Scheduled task is completed.")
                // can't return, it needs to be continue running
            case <- death:
                //do any clean up you need and return
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用