Last active
October 15, 2023 21:00
-
-
Save gillesdemey/1d04edc86b8a08debd0225d7989286f8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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