Skip to content
This repository has been archived by the owner on Feb 20, 2024. It is now read-only.

Setting Timeouts or Deadlines

Robert Catmull edited this page Nov 10, 2020 · 4 revisions

If your workers needs to stop at a deadline or you just need to have a timeout use the SetTimeout or SetDeadline methods. Worker functions backbone is errgroups, because of this when you look for the signal (IsDone() as seen below), you need to return an error and handle it otherwise the errgroup will wait for your worker functions to be finish causing deadlock.

 // Setting a timeout of 2 seconds
 timeoutWorker.SetTimeout(2 * time.Second)

 // Setting a deadline of 4 hours from now
 deadlineWorker.SetDeadline(time.Now().Add(4 * time.Hour))

func (my *MyWorker) Work(w *worker.Worker) error {
	for {
		select {
		case in := <-w.In():
			fmt.Println(in)
			time.Sleep(1 * time.Second)
		case <-w.IsDone():
			// due to the nature of errgroups in order to stop the worker from
			// waiting an error needs to be returned
			return fmt.Errorf("timeout reached")
		}
	}
}
Clone this wiki locally