Skip to content

Instantly share code, notes, and snippets.

@icholy
Last active September 30, 2020 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icholy/5d140f0f0000a97904c66b6cd64a5b78 to your computer and use it in GitHub Desktop.
Save icholy/5d140f0f0000a97904c66b6cd64a5b78 to your computer and use it in GitHub Desktop.
package contextutil
import (
"context"
"time"
)
// ResetFunc resets the context timeout timer
type ResetFunc func()
// WithTimeoutReset returns a child context which is canceled after the provided duration elapses.
// The returned ResetFunc may be called before the context is canceled to restart the timeout timer.
// Unlike context.WithTimeout, the returned context will not report the correct deadline.
func WithTimeoutReset(parent context.Context, d time.Duration) (context.Context, context.CancelFunc, ResetFunc) {
ctx, cancel0 := context.WithCancel(parent)
timer := time.AfterFunc(d, cancel0)
cancel := func() {
cancel0()
timer.Stop()
}
reset := func() {
timer.Reset(d)
}
return ctx, cancel, reset
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment