Skip to content

Instantly share code, notes, and snippets.

@gildas
Created June 30, 2021 14:37
Show Gist options
  • Save gildas/7134a5a3f829b044b5a769892fc21eee to your computer and use it in GitHub Desktop.
Save gildas/7134a5a3f829b044b5a769892fc21eee to your computer and use it in GitHub Desktop.
package main
import (
"context"
"time"
"github.com/gildas/go-errors"
"github.com/gildas/go-logger"
)
func fastjob(result chan interface{}) {
time.Sleep(50 * time.Millisecond)
result <- "Job Done"
}
func slowjob(result chan interface{}) {
time.Sleep(10 * time.Second)
result <- "Job Done"
}
func jobRunner(ctx context.Context, job func(chan interface{})) error {
log := logger.Must(logger.FromContext(ctx))
reschan := make(chan interface{})
// Run the job
go job(reschan)
// Wait for results
start := time.Now()
for {
select {
case result := <-reschan:
log.Infof("Success results: %+v in %s", result, time.Since(start))
return nil
case <-ctx.Done():
log.Errorf("Timeout encountered after %s", time.Since(start))
return errors.HTTPStatusRequestTimeout.WithStack()
}
}
}
func main() {
log := logger.Create("CONTEXT", &logger.StdoutStream{Unbuffered: true})
logctx := log.ToContext(context.Background())
log.Infof("Running a fast job")
log1 := log.Record("job", "fastjob")
ctx1, cancel1 := context.WithTimeout(logctx, 1 * time.Second)
defer cancel1()
if err := jobRunner(ctx1, fastjob); err != nil {
log1.Errorf("Error was encountered", err)
}
log.Infof("Running a slow job")
log2 := log.Record("job", "slowjob")
ctx2, cancel2 := context.WithTimeout(logctx, 1 * time.Second)
defer cancel2()
if err := jobRunner(ctx2, slowjob); err != nil {
log2.Errorf("Error was encountered", err)
}
}
@gildas
Copy link
Author

gildas commented Jun 30, 2021

Logger output:

23:38:06.000  INFO CONTEXT: Running a fast job (scope=main, tid=2645317, topic=main)
23:38:06.000  INFO CONTEXT: Success results: Job Done in 50.196358ms (scope=main, tid=2645320, topic=main)
23:38:06.000  INFO CONTEXT: Running a slow job (scope=main, tid=2645320, topic=main)
23:38:07.000 ERROR CONTEXT: Timeout encountered after 1.001048114s (scope=main, tid=2645319, topic=main)
23:38:07.000 ERROR CONTEXT: (err={}, job=slowjob, scope=main, tid=2645319, topic=main)
    Error was encountered, Error: Request Timeout
    github.com/gildas/go-errors.WithStack
    	.../go-errors@v0.1.1/wrappers.go:27
    github.com/gildas/go-errors.Error.WithStack
    	.../go-errors@v0.1.1/error.go:117
    main.jobRunner
    	.../context-timeout.go:37
    main.main
    	.../context-timeout.go:58
    runtime.main
    	/go/runtime/proc.go:225
    runtime.goexit
    	go/runtime/asm_amd64.s:1371

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment