×

Welcome to TagMyCode

Please login or create account to add a snippet.
1
0
 
0
Language: Ruby
Posted by: petecocoon
Added: Jul 11, 2011 7:49 AM
Modified: Jul 11, 2011 11:32 AM
Views: 581
This class allow to execute an async methods every n seconds like setTimeout in javascript.
For example
test = Timer.new(1) do
puts 'Hello'
end

Print on screen 'Hello' every 1 second until test.stop called.
The process can be restarted with test.start
  1. require 'monitor'
  2.  
  3. class Timer
  4.    def initialize(interval, &handler)
  5.      raise ArgumentError, "Interval less than zero" if interval < 0
  6.      extend MonitorMixin
  7.      @handler = handler
  8.      @interval = interval
  9.      start
  10.    end
  11.  
  12.    def start
  13.     return if @run
  14.     @run = true
  15.     @th = Thread.new do
  16.       t = Time.now
  17.       while run?
  18.         t += @interval
  19.         (sleep(t - Time.now) rescue nil) and @handler.call rescue nil
  20.      end
  21.     end
  22.    end
  23.    
  24.    def stop
  25.      synchronize do
  26.        @run = false
  27.      end
  28.      @th.join
  29.    end
  30.  
  31.    private
  32.  
  33.    def run?
  34.      synchronize do
  35.        @run
  36.      end
  37.    end
  38. end