Skip to content

Instantly share code, notes, and snippets.

@gillesdemey
Last active October 15, 2023 21:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gillesdemey/1d04edc86b8a08debd0225d7989286f8 to your computer and use it in GitHub Desktop.
Save gillesdemey/1d04edc86b8a08debd0225d7989286f8 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"github.com/oklog/run"
"log"
"syscall"
"time"
)
func main() {
group := new(run.Group)
ctx := context.Background()
// add signal handler to the run group
group.Add(run.SignalHandler(ctx, syscall.SIGINT, syscall.SIGTERM))
// execute async fns with timeout
// play with these values to trigger errors
group.Add(sleepWithTimeout(ctx, 1 * time.Second, 3 * time.Second))
log.Println("Running...")
err := group.Run()
if err != nil {
log.Fatal("Program exit: ", err)
}
log.Println("Done")
}
func sleepWithTimeout(ctx context.Context, sleep time.Duration, timeout time.Duration) (execute func() error, interrupt func(error)) {
ctx, cancel := context.WithTimeout(ctx, timeout)
execute = func() error {
err := sleepContext(ctx, sleep)
return err
}
interrupt = func(err error) {
cancel()
}
return execute, interrupt
}
func sleepContext(ctx context.Context, delay time.Duration) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(delay):
return ctx.Err()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment