diff --git a/background.go b/background.go index 2f01648..a8ceb97 100644 --- a/background.go +++ b/background.go @@ -10,9 +10,7 @@ import ( "math" "math/rand" "os" - "os/signal" "sync" - "syscall" "time" "github.com/hibiken/asynq/internal/base" @@ -252,18 +250,7 @@ func (bg *Background) Run(handler Handler) { bg.logger.Info("Send signal TSTP to stop processing new tasks") bg.logger.Info("Send signal TERM or INT to terminate the process") - // Wait for a signal to terminate. - sigs := make(chan os.Signal, 1) - signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT, syscall.SIGTSTP) - for { - sig := <-sigs - if sig == syscall.SIGTSTP { - bg.processor.stop() - bg.ps.SetStatus(base.StatusStopped) - continue - } - break - } + bg.waitForSignals() fmt.Println() bg.logger.Info("Starting graceful shutdown") } diff --git a/go.mod b/go.mod index 67c3abd..02cba88 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/rs/xid v1.2.1 github.com/spf13/cast v1.3.1 go.uber.org/goleak v0.10.0 - golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e // indirect + golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 gopkg.in/yaml.v2 v2.2.7 // indirect ) diff --git a/signals_unix.go b/signals_unix.go new file mode 100644 index 0000000..f68124e --- /dev/null +++ b/signals_unix.go @@ -0,0 +1,30 @@ +// +build linux bsd darwin + +package asynq + +import ( + "os" + "os/signal" + + "golang.org/x/sys/unix" + + "github.com/hibiken/asynq/internal/base" +) + +// waitForSignals waits for signals and handle them. +// It handles SIGTERM, SIGINT, and SIGTSTP. +// SIGTERM and SIGINT will signal the process to exit. +// SIGTSTP will signal the process to stop processing new tasks. +func (bg *Background) waitForSignals() { + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, unix.SIGTERM, unix.SIGINT, unix.SIGTSTP) + for { + sig := <-sigs + if sig == unix.SIGTSTP { + bg.processor.stop() + bg.ps.SetStatus(base.StatusStopped) + continue + } + break + } +} diff --git a/signals_windows.go b/signals_windows.go new file mode 100644 index 0000000..10aa0a1 --- /dev/null +++ b/signals_windows.go @@ -0,0 +1,21 @@ +// +build windows + +package asynq + +import ( + "os" + "os/signal" + + "golang.org/x/sys/windows" +) + +// waitForSignals waits for signals and handle them. +// It handles SIGTERM, SIGINT. +// SIGTERM and SIGINT will signal the process to exit. +// +// Note: Currently SIGTSTP is not supported for windows build. +func (bg *Background) waitForSignals() { + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, windows.SIGTERM, windows.SIGINT) + <-sigs +}