Created
October 11, 2011 15:01
-
-
Save rklemme/1278320 to your computer and use it in GitHub Desktop.
Timer example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment