njh / ruby-mqtt

Pure Ruby gem that implements the MQTT protocol, a lightweight protocol for publish/subscribe messaging.
http://www.rubydoc.info/gems/mqtt
MIT License
542 stars 135 forks source link

How to handle sigterm? #145

Closed 9mm closed 3 months ago

9mm commented 2 years ago

I'm using this in a sidekiq job (not the best place for it I realize, in the name of time I'm not daemonizing)

The only thing is, is there a way I can check something inside the local loop in the gem?

This obviously only works when there's a message, but otherwise it will get SIGKILL

      client.get do |topic, message|
        break if $sidekiq_shutdown_pending
        puts topic, message
      end
softwaregravy commented 2 years ago

You can rescue interrupts in Ruby. Here's a blogpost (not mine) talking a bit about it. So you'd have to wrap the code in a begin block and then rescue the interrupt.

If instead of what you have there, you were to do:

MQTT::Client.connect(...) do |c|
   ...
end

Then your code would be wrapped in an ensure block which should exit cleanly.

9mm commented 2 years ago

awesome thank you

dentarg commented 3 months ago

You can also define your own signal handlers: https://ruby-doc.org/3.3.3/Signal.html, https://github.com/ruby/ruby/blob/master/doc/signals.rdoc (Signal.trap)

dentarg commented 3 months ago

I think this issue should be closed. It is more a general Ruby question, and not something to be addressed in this gem.