description | signalcontext |
owner | Joe Wreschnig |
last change | Mon, 15 Jun 2020 21:20:19 +0000 (23:20 +0200) |
URL | https://git.korewanetadesu.com/go-signalcontext.git |
signalcontext
A signalcontext.Context
provides a context.Context
which cancels
when an operating system signal (e.g. os.Interrupt) is received.
This can be useful to bound some long or infinite operation running near
the top-level of a program so the rest of the program can
proceed with a clean shutdown.
Using this module correctly requires some knowledge of the standard context package. In its simplest form it can be used exactly like any other context, e.g. to read from a sarama ConsumerGroup until an interrupt is received:
parent := context.Background() // for example
ctx := signalcontext.UntilSignal(parent, os.Interrupt)
var err error
for err == nil {
select {
case <-ctx.Done():
err = ctx.Err()
default:
err = consumer.Consume(ctx, topics, hander)
}
}
ctx.Cancel()
return err
A more advanced use would be to push decisions about acceptable cleanup times out of the process, into an orchestration layer that communicates by sending signals:
parent := context.Background() // for example
srv := &http.Server{…}
// Run an HTTP server until a SIGTERM is received…
srvctx := signalcontext.UntilSignal(parent, syscall.SIGTERM)
go func() {
handleError(srv.ListenAndServe())
srvctx.Cancel()
}()
<-srvctx.Done()
// no need to cancel, srvctx must be done by now.
// Then try a clean shutdown, giving up if a second SIGTERM is received.
shutdownctx := signalcontext.UntilSignal(parent, syscall.SIGTERM)
defer shutdownctx.Cancel()
return srv.Shutdown(srvctx)
Copyright 2020 Joe Wreschnig
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
2020-06-15 | Joe Wreschnig | Add project documentation and licensing master | commit | commitdiff | tree |
2020-06-14 | Joe Wreschnig | Reuse the same channel for all precompleted contexts | commit | commitdiff | tree |
2020-06-14 | Joe Wreschnig | Add a benchmark for precompleted context creation | commit | commitdiff | tree |
2020-06-14 | Joe Wreschnig | Improve Error.Error() performance | commit | commitdiff | tree |
2020-06-14 | Joe Wreschnig | Remove ‘Signal’ from structure names | commit | commitdiff | tree |
2020-06-14 | Joe Wreschnig | Initial import | commit | commitdiff | tree |
4 years ago | master | shortlog | log | tree |