#
# timer.rb
#
# Copyright (c) 1999-2002 Minero Aoki <aamine@loveruby.net>
#
# This program is free software.
# You can distribute/modify this program under the terms of
# the GNU Lesser General Public License version 2 or later.
#
# $Id: timer.rb,v 1.8 2002/01/05 06:46:49 aamine Exp $
#
# Usage:
#
# t = Timer.new(10) { raise TimeoutError, "timeout!" }
# t.start
# : # done with 10sec timeout
# t.stop
#
# t.start
# :
# if condition then
# t.reset #--> restart timer
# end
#
require 'timeout' # for TimeoutError
class Timer
def initialize( s, &block )
@sec = s
@on_timeout = block
@current = nil
@timer_thread = nil
end
attr_accessor :sec
def on_timeout( &block )
if block then
@on_timeout = block
true
else
false
end
end
def start
@current = Thread.current
@timer_thread = Thread.fork {
sleep @sec
if @on_timeout then
@on_timeout.call @sec
else
@current.raise TimeoutError "#{@sec} seconds past"
end
}
if iterator? then
begin
yield
ensure
stop
end
else
@sec
end
end
def stop
if @timer_thread then
Thread.kill @timer_thread
@timer_thread = nil
true
else
false
end
end
def reset
stop
start
end
end
class DammyTimer < Timer
def start
if iterator? then
yield
else
sec()
end
end
def stop
false
end
end
syntax highlighted by Code2HTML, v. 0.9.1