Class: IRC::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/rhuidean/timer.rb

Overview

Allows for code to be executed on a timed basis.

Constant Summary collapse

@@timers =

class attributes

[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(time, repeat = false, &block) ⇒ Timer

Creates a new timer to be executed within +10 seconds of time.


time

time in seconds

repeat

true or false, keep executing block every time?

block

execute the given block

returns

self



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rhuidean/timer.rb', line 28

def initialize(time, repeat = false, &block)
    @time    = time.to_i
    @timeout = Time.now.to_f + @time
    @repeat  = repeat
    @block   = block

    @@timers << self

    @thread = Thread.new { start }

    self
end

Instance Attribute Details

#repeatObject (readonly)

instance attributes



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

def repeat
  @repeat
end

#timeObject (readonly)

instance attributes



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

def time
  @time
end

#timeoutObject (readonly)

instance attributes



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

def timeout
  @timeout
end

Class Method Details

.after(time, &block) ⇒ Object

A wrapper for initialize. Sets up so the block doesn’t repeat.


time

execute block after how long, in seconds?

returns

self



61
62
63
# File 'lib/rhuidean/timer.rb', line 61

def Timer.after(time, &block)
    new(time, false, &block)
end

.every(time, &block) ⇒ Object

A wrapper for initialize. Sets up the block to repeat. –

time

repeat how often, in seconds?

returns

self



51
52
53
# File 'lib/rhuidean/timer.rb', line 51

def Timer.every(time, &block)
    new(time, true, &block)
end

.next_timeObject

Returns the Unix timestamp of the next time a timer should run


returns

minimum timer interval, see above



70
71
72
73
# File 'lib/rhuidean/timer.rb', line 70

def Timer.next_time
    return 0 if @@timers.empty?
    @@timers.collect { |t| t.timeout }.min
end

.stopObject

Stops all timers.


returns

nothing



80
81
82
# File 'lib/rhuidean/timer.rb', line 80

def Timer.stop
    @@timers.each { |t| t.stop }
end

Instance Method Details

#stopObject

Kills the thread we’re in.


returns

nothing



89
90
91
92
# File 'lib/rhuidean/timer.rb', line 89

def stop
    @@timers.delete(self)
    @thread.exit
end