Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created October 11, 2011 15:01
Show Gist options
  • Save rklemme/1278320 to your computer and use it in GitHub Desktop.
Save rklemme/1278320 to your computer and use it in GitHub Desktop.
Timer example
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