TorqueBox makes it really easy to send jobs to a background process, similiar to Delayed Job or Resque, only you dont need to run and monitor yet another system, it’s all contained in the TorqueBox app server (which is actually JBOSS).
However, if you are going to be doing something ActiveRecord-y in the background, there are a few things you need to realize. When you use ActiveRecord in Rails, a middleware is installed that closes database connections and returns them to the connection pool after each web request. But when you are using ActiveRecord outside of a web request cycle, you need to worry about the connections yourself.
If you dont do anything, and you use ActiveRecord in your TorqueBox background processes or message queues, eventually you will run out of database connections, as they are not being closed. You can track this issue here.
The convention in Rails for handling connections yourself goes like this:
1 2 3
This ensures that after you are done with the connection it gets closed. But using this technique is a bit awkward when using background processes. Plus you have to remember to do it every time. Another approach is to monkey patch the MessageProcessor class like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Here we just add an
ensure block to make sure we always clear out the connections when we are done. This will apply to all message processors, which includes the Backgroundable processor.
It looks like there are some chainable middleware constructs that could be used to do this in a cleaner way. That’s a project for another day.