Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'monitor'
- class Timer
- # include MonitorMixin
- def self.repeat_every(interval_sec, &code)
- t = Timer.new(interval_sec, code)
- t.start
- t
- end
- def initialize(interval, code)
- extend MonitorMixin
- @interval = interval
- @code = code
- end
- def start
- synchronize do
- raise "Already running" if @thread
- @stop = false
- @thread = Thread.new do
- intv = synchronize { @interval }
- until synchronize { @stop }
- t = Time.now
- @code.call
- sleep(t + intv - Time.now)
- end
- synchronize { @thread = nil }
- end
- end
- self
- end
- def stop
- synchronize do
- @stop = true
- end
- self
- end
- def shutdown
- th = synchronize do
- @stop = true
- @thread
- end
- th.join if th
- self
- end
- end
- t = Timer.repeat_every 1 do
- puts "foo"
- end
- sleep 20
- t.stop
Add Comment
Please, Sign In to add comment