Author:: Jared Kuolt (mailto:me@superjared.com)
Copyright:: Copyright (c) 2009 Jared Kuolt
License:: MIT License
= RobustThread
This module allows for the creation of a thread that will not simply die when
the process dies. Instead, it joins all RobustThreads in Ruby's exit handler.
== Installation
sudo gem install robustthread
== Usage
rt = RobustThread.new(:args => args, :label => "do_something with x and y") do |x, y|
do_something(x, y)
end
Options:
- +args+: arguments passed to the thread
- +label+: an identifier (used primarily in logs for debugging, defaults to
+thread.inspect+)
=== Easy Looping
You can loop a task in a thread to cleanly exit:
RobustThread.loop(:seconds => 3) do
do_something
end
Options are the same as RobustThread#new, with the addition of +seconds+, the
interval at which the Thread will sleep.
=== Exception Handling
Since Threads usually eat exceptions, RobustThread allows for a simple global
exception handler:
RobustThread.exception_handler do |exception|
# Handle your exceptions here
end
If no handler is assigned, the exception traceback will be piped into the
logger as an error message.
=== Callbacks
RobustThread currently supports 5 callbacks. The following 4 are called per
RobustThread.
RobustThread.add_callback(:before_init){ puts "Before init!" }
RobustThread.add_callback(:before_yield){ puts "Before yield!" }
RobustThread.add_callback(:after_yield){ puts "After yield!" }
RobustThread.add_callback(:after_join){ puts "After join!" }
The +before_exit+ callback is called after all threads are re-joined.
RobustThread.add_callback(:before_exit){ puts "Before exit!" }
=== Etc...
If necessary, you can access the actual thread from the RobustThread
object via its +thread+ attribute.
rt.thread
=> #<Thread:0x7fa1ea57ff88 run>
By default, RobustThread uses a Logger that defaults itself to STDOUT. You
can change this by assigning the +logger+ class attribute to a different
Logger object:
RobustThread.logger = Logger.new(STDERR)