Class: TimeoutX

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/timeoutx.rb

Defined Under Namespace

Modules: Version Classes: Error

Constant Summary collapse

VERSION =
Version::STRING

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTimeoutX

:nodoc:



20
21
22
23
24
25
26
27
28
29
# File 'lib/timeoutx.rb', line 20

def initialize #:nodoc:
  @table = {}
  @interval = 0.5
  @thread = Thread.start do
    while true
      sleep(@interval)
      countdown
    end
  end
end

Instance Attribute Details

#intervalObject

Returns the value of attribute interval.



16
17
18
# File 'lib/timeoutx.rb', line 16

def interval
  @interval
end

#tableObject (readonly)

Returns the value of attribute table.



18
19
20
# File 'lib/timeoutx.rb', line 18

def table
  @table
end

#threadObject (readonly)

Returns the value of attribute thread.



17
18
19
# File 'lib/timeoutx.rb', line 17

def thread
  @thread
end

Class Method Details

.append(th, sec, exception) ⇒ Object

:nodoc:



46
47
48
# File 'lib/timeoutx.rb', line 46

def self.append(th, sec, exception) #:nodoc:
  instance.table[th] = [sec, exception]
end

.delete(th) ⇒ Object

:nodoc:



50
51
52
# File 'lib/timeoutx.rb', line 50

def self.delete(th) #:nodoc:
  instance.table.delete(th)
end

.replace_timeoutObject

Replaces Timeout.timeout into TimeoutX.timeout.



67
68
69
70
71
72
# File 'lib/timeoutx.rb', line 67

def self.replace_timeout
  require "timeout"
  def Timeout.timeout(sec, exception=Timeout::Error) #:nodoc:
    TimeoutX.timeout(sec, exception)
  end
end

.set_interval(sec) ⇒ Object

Sets the interval second of intrenal countdown loop.



32
33
34
# File 'lib/timeoutx.rb', line 32

def self.set_interval(sec)
  instance.interval = sec
end

.timeout(sec, exception = TimeoutX::Error) ⇒ Object

Same as Timeout#timeout.



55
56
57
58
59
60
61
62
63
64
# File 'lib/timeoutx.rb', line 55

def self.timeout(sec, exception=TimeoutX::Error)
  append(Thread.current, sec, exception)
  begin
    yield if block_given?
  rescue => ex
    raise(ex)
  ensure
    delete(Thread.current)
  end
end

Instance Method Details

#countdownObject

:nodoc:



36
37
38
39
40
41
42
43
44
# File 'lib/timeoutx.rb', line 36

def countdown #:nodoc:
  @table.each do |th, attr|
    attr[0] -= @interval
    if attr[0] <= 0
      th.raise(attr[1], "execution expired") if th.alive?
      @table.delete(th)
    end
  end
end