+
+ def running?
+ @thread && @thread.alive?
+ end
+
+ # return the number of seconds until the next action is due, or 0 if
+ # none are outstanding - will only be accurate immediately after a
+ # tick()
+ def next_action_time
+ @next_action_time
+ end
+
+ # start the timer, it spawns a thread to tick the timer, intelligently
+ # shutting down if no events remain and starting again when needed.
+ def start
+ return if running?
+ @should_be_running = true
+ start_thread unless @timers.empty?
+ end
+
+ # stop the timer from ticking
+ def stop
+ @should_be_running = false
+ stop_thread
+ end
+
+ private
+
+ def start_on_add
+ if running?
+ stop_thread
+ start_thread
+ elsif @should_be_running
+ start_thread
+ end
+ end
+
+ def stop_thread
+ return unless running?
+ @thread.kill
+ end
+
+ def start_thread
+ return if running?
+ @thread = Thread.new do
+ while(true)
+ tick
+ exit if @timers.empty?
+ sleep(@next_action_time)
+ end
+ end
+ end
+