Last active
September 30, 2020 00:47
-
-
Save icholy/5d140f0f0000a97904c66b6cd64a5b78 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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