dougaicha5258 2019-02-01 14:04
浏览 24
已采纳

如何从长期运行的goroutine发送更新?

I have a goroutine for a long running job. When the job is done, it pushes the results to a channel. In the meantime, while the job is running, I want to keep updating an API with the status RUNNING.

So far, I have the following code :

func getProgressTimeout() <-chan time.Time {
    return time.After(5 * time.Minute)
}

func runCommand(arg *Request) {
    chanResult := make(chan Results)

    go func(args *Request, c chan Results) {
        resp, err := execCommand(args)
        c <- Results{
            resp: resp,
            err:  err,
        }
    }(arg, chanResult)

    var err error

progressLoop:
    for {
        select {
        case <-getProgressTimeout():
            updateProgress()  // this method will send status= RUNNING to a REST API

        case out := <-chanResult:
            err = jobCompleted(request, out)
            break progressLoop
        }
    }
    return err
}

I am new to golang. And I have reached the above code after lot of trial and error, and googling. It's working now. Still it doesn't feel intuitive to me when I look at it (this may very well be because, I am still trying to learn the Go way of doing things). So my question is, can I refactor this into better shape? Is there some existing pattern which is applicable in this kind of scenario? Or if there is some totally different approach to keep sending periodic updates while job is running?

Also, any suggestions to improve upon my golang concurrency are also appreciated. :)

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • drrkgbm6851 2019-02-01 14:15
    关注

    Consider using time.NewTicker, which sends a periodic value to a channel. Here's an example from the documentation:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        ticker := time.NewTicker(time.Second)
        defer ticker.Stop()
        done := make(chan bool)
        go func() {
            time.Sleep(10 * time.Second)
            done <- true
        }()
        for {
            select {
            case <-done:
                fmt.Println("Done!")
                return
            case t := <-ticker.C:
                fmt.Println("Current time: ", t)
            }
        }
    }
    

    Note that the embedded goroutine invoking func emulates a long task by sleeping for 10 seconds, while the caller uses select to wait for the result, while also receiving periodic events from the ticker - this is where you can do the API progress update.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线