开始-如何设置计时器。停止正常工作

时间:2019-05-24 14:26:33

标签: go timer

我想知道我的代码在这里做错了什么。流程描述如下:

  • 我有一个任务,该任务在一定时间后超时。该任务是具有timer *time.Timer属性的完整结构。当任务准备就绪时,我会按照建议的Here使用time.NewTimer(duration * time.Second)来启动它
  • 我连接到服务,这会引发错误。如果是这样,我必须停止计时器并执行几行代码
  • 我有等待事件的频道监听器

所以现在的问题是,即使我调用t.timer.Stop()也无法接收到使它停止的信号。还是我错了?

下面是代码,我用“ ***”注释,这对我的情况很重要

在发现错误之后,我已经打电话给t.timer.Stop(),但没有成功

现在,我添加了新的频道sigError,以便能够在选择循环中捕获此上下文中的错误

func (t *Task) Listen(queue chan<- *Task, w *Worker) {
    if err := t.ableToConnect(); err != nil {
        log.Errorf("TASK", "Condition not satisfied -> %s", err, t)

        //t.Release()
        return
    }

    log.Infof("TASK", "processing task on worker %s", t.w.Id(), t)

        // *** This is used mostly to signal that an error has occurred during main process 
    sigError := make(chan *error, 1)

    // fetch item from podio
    push := podio.Push{Channel: fmt.Sprintf("/item/%d", t.ItemId), ExpiresIn: 120}
    t.setTimout(push.ExpiresIn)

    // connect to podio push
    messages := make(chan *bayeux.Message)
    if err := push.Subscribe(w.faye, messages); err != nil {
                // *** Here I signal the error
        sigError <- &err
    }

    // loop and check channels (timer and tasks)
    for {
        select {
        case err := <-sigError:
            // *** This statement is executed as it should
            log.Errorf("TASK", "Cannot subscribe -> %s...", *err, push)
            t.timer.Stop()

        case <-t.timer.C:
                        // *** Below is few lines of code I talked earlier and it is not executed at all. But unfortunately the code is never get here unless the duration has expired

        default:
        }
    }
}

目标是如果当前任务抛出错误或过期,则能够使用相同的参数创建新任务

0 个答案:

没有答案