Class: Time::Limit

Inherits:
Object show all
Defined in:
lib/carat/timelimit.rb

Overview

Time::Limit

Direct Known Subclasses

Dummy

Defined Under Namespace

Classes: Dummy

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(s, &block) ⇒ Limit

Returns a new instance of Limit.



40
41
42
43
44
45
# File 'lib/carat/timelimit.rb', line 40

def initialize( s, &block )
  @sec = s
  @on_timeout = block
  @current = nil
  @timer_thread = nil
end

Instance Attribute Details

#secObject

Returns the value of attribute sec.



47
48
49
# File 'lib/carat/timelimit.rb', line 47

def sec
  @sec
end

Instance Method Details

#on_timeout(&block) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/carat/timelimit.rb', line 49

def on_timeout( &block )
  if block then
    @on_timeout = block
    true
  else
    false
  end
end

#resetObject



89
90
91
92
# File 'lib/carat/timelimit.rb', line 89

def reset
  stop
  start
end

#startObject



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/carat/timelimit.rb', line 58

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

#stopObject



79
80
81
82
83
84
85
86
87
# File 'lib/carat/timelimit.rb', line 79

def stop
  if @timer_thread then
    Thread.kill @timer_thread
    @timer_thread = nil
    true
  else
    false
  end
end