Forum: Ruby timer

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
angico (Guest)
on 2008-10-21 00:30
(Received via mailing list)
Hi, All.

Can anybody tell me how to implement kind of a timer in Ruby, similar to
the following one from Java?

timer = new Timer( 200, handler ); // call handler each 200 milliseconds


Thank you,

--

angico
------
home page: www.angico.org
Gnu/Linux, FLOSS, Espiritismo, e eu por mim mesmo 8^I
Robert K. (Guest)
on 2008-10-21 01:05
(Received via mailing list)
On 20.10.2008 22:28, angico wrote:
> [Note:  parts of this message were removed to make it a legal post.]
>
> Hi, All.
>
> Can anybody tell me how to implement kind of a timer in Ruby, similar to
> the following one from Java?
>
> timer = new Timer( 200, handler ); // call handler each 200 milliseconds

Here's a simple one

#!/bin/env ruby

require 'monitor'

class Timer
   def initialize(interval, &handler)
     raise ArgumentError, "Illegal interval" if interval < 0
     extend MonitorMixin
     @run = true
     @th = Thread.new do
       t = Time.now
       while run?
  t += interval
  (sleep(t - Time.now) rescue nil) and
    handler.call rescue nil
       end
     end
   end

   def stop
     synchronize do
       @run = false
     end
     @th.join
   end

   private

   def run?
     synchronize do
       @run
     end
   end
end

t = Timer.new(1) do
   puts "tick #{Time.now.to_f}"
   # random sleep to show slot stability
   sleep((5 + rand(10))/10.0)
end

sleep 10
t.stop
Brian C. (Guest)
on 2008-10-21 01:13
angico wrote:
> Hi, All.
>
> Can anybody tell me how to implement kind of a timer in Ruby, similar to
> the following one from Java?
>
> timer = new Timer( 200, handler ); // call handler each 200 milliseconds

If your handler is short and you don't care too much about accuracy:

Thread.new { loop { handler; sleep 0.2 } }
Joel VanderWerf (Guest)
on 2008-10-21 01:36
(Received via mailing list)
angico wrote:
> Hi, All.
>
> Can anybody tell me how to implement kind of a timer in Ruby, similar to
> the following one from Java?
>
> timer = new Timer( 200, handler ); // call handler each 200 milliseconds

This is what I use:

http://redshift.sourceforge.net/timer/timer.rb

It's pretty simple, and it corrects for the time taken by the handler.
This topic is locked and can not be replied to.