| Class | Timer |
| In: |
lib/more/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 Kernel method is also provided for easily timing the exectuion of a block.
timed { |timer|
timer.total_time.round #=> 0
sleep 1
timer.total_time.round #=> 1
timer.stop
timer.total_time.round #=> 1
sleep 2
timer.total_time.round #=> 1
timer.start
timer.total_time.round #=> 1
sleep 1
timer.total_time.round #=> 2
}
| end_time | [R] | |
| start_time | [R] | |
| time_limit | [RW] |
# File lib/more/facets/timer.rb, line 110
110: def initialize( time_limit=nil, &block )
111: # standard timer
112: @start_time = nil
113: @end_time = nil
114: @total_time = 0
115: @runnning = nil
116: # for using time limit
117: @time_limit = time_limit
118: @on_timeout = block
119: @current_thread = nil
120: @timer_thread = nil
121: end
Establish a time limit on execution.
# File lib/more/facets/timer.rb, line 155
155: def limit( time_limit=nil )
156: if @time_limit || time_limit
157: @current_thread = Thread.current
158: @timer_thread = Thread.fork {
159: sleep @time_limit
160: if @on_timeout then
161: @on_timeout.call @time_limit
162: else
163: @current_thread.raise TimeoutError, "#{@time_limit} seconds past"
164: end
165: }
166: end
167: end
# File lib/more/facets/timer.rb, line 123
123: def on_timeout( &block )
124: if block then
125: @on_timeout = block
126: true
127: else
128: false
129: end
130: end
Stops and resets the timer. If the timer was running returns the total time. If not returns 0.
# File lib/more/facets/timer.rb, line 196
196: def reset
197: if running?
198: r = stop
199: else
200: r = 0
201: end
202: @total_time = 0
203: return r
204: end
Queries whether the timer is still running.
# File lib/more/facets/timer.rb, line 221
221: def running?
222: return @running
223: end
Start the timer.
# File lib/more/facets/timer.rb, line 134
134: def start
135: @running = true
136: @start_time = Time.now
137:
138: limit if @time_limit
139:
140: self
141:
142: #if block_given? then
143: # begin
144: # yield( self )
145: # ensure
146: # stop
147: # end
148: #else
149: # @time_limit
150: #end
151: end
Stops timer and returns total time. If timer was not running returns false.
# File lib/more/facets/timer.rb, line 181
181: def stop
182: if @running
183: defuse
184: # record running time
185: @end_time = Time.now
186: @running = false
187: @total_time += (@end_time - @start_time)
188: else
189: nil
190: end
191: end
Queries whether the timer is still not running.
# File lib/more/facets/timer.rb, line 227
227: def stopped?
228: return !@running
229: end