Class | Timer |
In: |
lib/facets/supplemental/facets/timer.rb
|
Parent: | Object |
Provides a strightforward means for controlling time critical execution. Can be used as a "stop watch" timer or as a "time bomb" timer:
t = Timer.new(10) { raise TimeoutError, "timeout!" } t.start : # done within 10sec timeout t.stop t.start : if condition then t.reset #--> restart timer end
A class method is also provided for easily timing the exectuion of a block.
Timer.time do |timer| timer.total_time.round #=> 0 sleep 1 timer.total_time.round #=> 1 timer.stop timer.total_time.round #=> 1 sleep 1 timer.total_time.round #=> 1 timer.start timer.total_time.round #=> 1 sleep 1 timer.total_time.round #=> 2 end
Thanks to Paul Brannan for TimeLimit and Minero Aoki for Timer. These two libraries served as models for building this class.
time_limit | [RW] |
# File lib/facets/supplemental/facets/timer.rb, line 45 def initialize(time_limit=nil, &block) # standard timer @start_time = nil @end_time = nil @total_time = 0 @runnning = nil # for using time limit @time_limit = time_limit @on_timeout = block @current_thread = nil @timer_thread = nil end
Establish a time limit on execution.
# File lib/facets/supplemental/facets/timer.rb, line 102 def limit( time_limit=nil ) if @time_limit || time_limit @current_thread = Thread.current @timer_thread = Thread.fork { sleep @time_limit if @on_timeout then @on_timeout.call @time_limit else @current_thread.raise TimeoutError, "#{@time_limit} seconds past" end } end end
# File lib/facets/supplemental/facets/timer.rb, line 72 def on_timeout( &block ) if block then @on_timeout = block true else false end end
Queries whether the timer is still running.
# File lib/facets/supplemental/facets/timer.rb, line 163 def running? return @running end
Start the timer.
# File lib/facets/supplemental/facets/timer.rb, line 82 def start @running = true @start_time = Time.now limit if @time_limit self ##if block_given? then ## begin ## yield( self ) ## ensure ## stop ## end ##else ## @time_limit ##end end
Queries whether the timer is still not running.
# File lib/facets/supplemental/facets/timer.rb, line 168 def stopped? return !@running end