philipbohun.com

Glojure by Example: Context

context.WithTimeout returns a context and a cancel function, as a vector. Err is nil until the deadline passes or cancel is called. Call cancel when the work is finished so the timer can be released.

(let [[ctx cancel] (context.WithTimeout (context.Background)
                                        (* 15 time.Millisecond))]
  (println "open" (nil? (.Err ctx)))
  (time.Sleep (* 40 time.Millisecond))
  (println "err" (.Error (.Err ctx)))
  (cancel))

Pass the context into Go APIs that accept one, such as a request or a command, when you want cancellation to propagate.

After the deadline the error is the standard timeout text.

$ glj context.glj
open true
err context deadline exceeded

Next example: Spawning Processes.