proxy.golang.org : github.com/icza/shutdown
Package shutdown helps controlling app shutdown and graceful termination of goroutines. It listens for SIGTERM (e.g. kill command) and SIGINT (e.g. CTRL+C) signals, and also provides a manual way to trigger shutdown. It publishes a single, shared shutdown channel which is closed when shutdown is about to happen. Modules (goroutines) should monitor this channel using a select statement, and terminate ASAP if it is (gets) closed. Additionally, there is an Initiated() function which tells if a shutdown has been initiated, which basically checks the shared channel in a non-blocking way. A context.Context is also published which will be cancelled when shutdown is about to happen. Background tasks requiring a context may use this directly or as a parent context. It also publishes a WaitGroup goroutines may use to "register" themselves should they wish to be patiently waited for and not get terminated abruptly. For this to "work", this shared WaitGroup must be "waited for" in the main() function before returning. If you just want to do something before shutting down: Note that monitoring the shutdown channel must be in the main goroutine and your task in another one (and not the other way), because the app terminates when the main() function returns. A more advanced example where a worker goroutine is to be waited for. This app also self-terminates after 10 seconds: Note that the above worker goroutine does not guarantee that it won't start execution of a new job after a shutdown has been initiated (because select chooses a "ready" case pseudo-randomly). If you need guarantee that no new jobs are taken after a shutdown initiation, you may check the shutdown channel first, in a separate select in a non-blocking way, or you may simply add the check as the loop condition like this: The following example starts a web server and provides graceful shutdown for it. It also handles abnormal (and silent) termination, in which case it triggers a manual shutdown, making sure the whole app gets terminated (not just its web server): The following example launches a background worker doing something that uses / requires a context.
Registry
-
Source
- Documentation
- JSON
purl: pkg:golang/github.com/icza/shutdown
License: Apache-2.0
Latest release: about 2 years ago
First release: over 2 years ago
Namespace: github.com/icza
Stars: 8 on GitHub
Forks: 0 on GitHub
See more repository details: repos.ecosyste.ms
Funding links: https://github.com/sponsors/icza
Last synced: 26 days ago