Class: Tmtms::Timer

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

Overview

Usage

Examples:

t = Tmtms::Timer.new
t.set(1){puts "hoge"}
sleep 5  # puts "hoge" after 1 second.

Defined Under Namespace

Classes: Job

Instance Method Summary collapse

Constructor Details

#initializeTimer

Returns a new instance of Timer.



29
30
31
32
33
34
# File 'lib/tmtms/timer.rb', line 29

def initialize
  @rfd, @wfd = IO.pipe
  @jobs = []  #=> [job, ...]
  @mutex = Mutex.new
  do_loop
end

Instance Method Details

#at(time, repeat: nil, &block) ⇒ Tmtms::Timer::Job

execute block at the specified time.

Parameters:

  • time (Time)
  • repeat (Numeric) (defaults to: nil)

    interval seconds

Returns:



48
49
50
51
52
53
54
55
56
# File 'lib/tmtms/timer.rb', line 48

def at(time, repeat: nil, &block)
  @mutex.synchronize do
    job = Job.new(timer: self, time: time, repeat: repeat, block: block)
    @jobs.push job
    @jobs.sort_by!(&:time)
    @wfd.syswrite('.')
    return job
  end
end

#cancel(job) ⇒ Tmtms::Timer::Job?

cancle the timer.

Parameters:

Returns:

  • (Tmtms::Timer::Job)

    if the job was available.

  • (nil)

    if the job was not available.



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

def cancel(job)
  @mutex.synchronize do
    @jobs.delete(job)
  end
end

#repeat(sec, &block) ⇒ Tmtms::Timer::Job

repeat block every sec seconds.

Parameters:

  • sec (Numeric)

    interval seconds

Returns:



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

def repeat(sec, &block)
  at(Time.now, repeat: sec, &block)
end

#set(sec, repeat: nil, &block) ⇒ Tmtms::Timer::Job

execute block after sec seconds.

Parameters:

  • sec (Numeric)
  • repeat (Numeric) (defaults to: nil)

    interval seconds

Returns:



40
41
42
# File 'lib/tmtms/timer.rb', line 40

def set(sec, repeat: nil, &block)
  at(Time.now + sec, repeat: repeat, &block)
end