Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Build Safer Ruby Daemons with RobustThread

By Ric Roberts / July 6, 2009

When running a Ruby daemon which executes code in a loop, if the process is killed while something is happening then problems can occur if the code doesn't handle all the exceptions properly or if the loop isn't broken cleanly. RobustThread is a Ruby class by Jared Kuolt for the creation of threads, which helps to alleviate this problem.

RobustThread lets you set up loggers, exception handlers and callbacks for threads, exposing the actual thread via an attribute.  By default, it logs to the standard output, but this is configurable by using a Logger object.

You can apply labels to loops or threads, which can be useful for logging and debugging.  But perhaps more importantly, by using RobustThread.loop, you can change the way that looping works so that it cleanly exits the loop on the next sleep call before rejoining the thread.

RobustThread.loop(:seconds => x) do
  do_something
end

Install RobustThread with gem install robustthread, or get the source from Github.  Jared provides some background and a few more examples on his blog.

Other Posts to Enjoy

Twitter Mentions