On 2002.06.07, nobu.nokada / softhome.net <nobu.nokada / softhome.net> wrote:
> Hi,
> 
> At Fri, 7 Jun 2002 02:19:52 +0900,
> Paul Brannan wrote:
> > I need to create an event that occurs exactly once per second.
> > (Understanding that this is impossible on Linux, I'm willing to accept a
> > solution that will average to exactly one event per second over the
> > course of a day).  Someone on irc suggested writing an extension that
> > calls setitimer, but 1) I've never used setitimer, so I don't know what
> > kinds of problems I might run into, and 2) I'd like a solution that
> > doesn't rely on SIGALRM, since that limits me to one timer per
> > application.
> 
> SIGALRM is used by the interpreter internally, so you can't use
> it.
> 
> require 'thread'
> event = ConditionVariable.new
> m = Mutex.new
> Thread.new do
>   loop do
>     sleep 1
>     event.signal
>   end
> end
> m.lock
> loop do
>   # ...
>   p Time.now
>   event.wait(m)
> end
> m.unlock

What about this:

def do_after(sec, &block)
  t = Thread.new(sec) {
      sleep sec
  }
  t.join
  yield
end

loop do
  do_after(1.0) {
    # ... stuff to do every second ...
  }
end
      
-- Dossy

-- 
Dossy Shiobara                       mail: dossy / panoptic.com 
Panoptic Computer Network             web: http://www.panoptic.com/ 
  "He realized the fastest way to change is to laugh at your own
    folly -- then you can let go and quickly move on." (p. 70)