title: Run function every N seconds with context timeout
body: <p>I have a basic question about scheduling &quot;cancellable&quot; goroutines.</p>
  <p>I want to schedule a function execution, every 3 seconds.</p>
  <p>The function can take up to 5 seconds.</p>
  <p>In case it takes more than 2999ms I want to stop/terminate it, to avoid overlapping w/ the next one.</p>
  <p>I'm doing it wrong:</p>
  <pre><code>func main() {
      fmt.Println(&quot;startProcessing&quot;)
      go startProcessing()
  
      time.Sleep(time.Second * 60)
      fmt.Println(&quot;endProcessing after 60s&quot;)
  }
  
  func startProcessing() {
      ticker := time.NewTicker(3 * time.Second)
      for _ = range ticker.C {
          ctx, _ := context.WithTimeout(context.Background(), (time.Second*3)-time.Millisecond)
  
          fmt.Println(&quot;start doSomething&quot;)
          doSomething(ctx)
      }
  }
  
  func doSomething(ctx context.Context) {
      executionTime := time.Duration(rand.Intn(5)+1) * time.Second
  
      for {
          select {
          case &lt;-ctx.Done():
              fmt.Printf(&quot;timed out after %s\n&quot;, executionTime)
              return
          default:
              time.Sleep(executionTime)
              fmt.Printf(&quot;did something in %s\n&quot;, executionTime)
              return
          }
      }
  }
  </code></pre>
  <p>This is my output now:</p>
  <blockquote>
  <p>startProcessing</p>
  <p>start doSomething</p>
  <p>did something in 2s</p>
  <p>start doSomething</p>
  <p>did something in 3s</p>
  <p>start doSomething</p>
  <p>did something in 3s</p>
  <p>start doSomething</p>
  <p>did something in 5s</p>
  <p>start doSomething</p>
  <p>did something in 2s</p>
  <p>...</p>
  </blockquote>
  <p>I want to read <code>timed out after 5s</code> instead of <code>did something in 5s</code>.</p>