typestar

Timeouts in Go

A select against time.After bounds how long you wait.

func withTimeout(work <-chan string, limit time.Duration) (string, error) {
    select {
    case result := <-work:
        return result, nil
    case <-time.After(limit):
        return "", fmt.Errorf("timed out after %s", limit)
    }
}

func tick(limit time.Duration) int {
    ticker := time.NewTicker(limit / 4)
    defer ticker.Stop()

    count := 0
    deadline := time.After(limit)
    for {
        select {
        case <-ticker.C:
            count++
        case <-deadline:
            return count
        }
    }
}

How it works

  1. time.After returns a channel that fires once.
  2. The losing branch is simply not taken.
  3. For repeated deadlines a Timer you can Stop leaks less.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
419
Tokens
111
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 3 of 3 in select, step 10 of 25 in Concurrency.

← Previous Next →