From: brabuhr@... Date: 2009-09-09T12:11:49+09:00 Subject: Re: Time based loop limiting On Tue, Sep 8, 2009 at 6:14 PM, Bertram Scharpf wrote: > Am Mittwoch, 09. Sep 2009, 01:38:33 +0900 schrieb Michael Tomer: >> I'm trying to write a loop that will only run a certain number of times >> per second. > > The proper way to do this is to call the setitimer(2) function > that will send SIGALRM periodically to the process. It has been > discussed a long time ago: > >  http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/130989 > > Still I cannot find a setitimer mapping in the Ruby interpreter. > So I wrote my own: > >  http://bertram-scharpf.homelinux.com:8808/doc_root/itimer-1.0/rdoc/index.html Took a shot with FFI: require 'ffi' module LibC extend FFI::Library class Timeval < FFI::Struct layout :tv_sec, :long, :tv_usec, :long end class Itimerval < FFI::Struct layout :it_interval, Timeval, :it_value, Timeval end attach_function :getitimer, [:int, :pointer], :int attach_function :setitimer, [:int, :pointer, :pointer], :int end Signal.trap("SIGALRM") do puts "SIGALRM: #{Time.now}" end tv = LibC::Timeval.new tv[:tv_sec] = 2 tv[:tv_usec] = 0 puts Time.now LibC::setitimer(0, tv, nil) sleep 15 puts Time.now #=> # Wed Sep 09 02:57:18 +0000 2009 # SIGALRM: Wed Sep 09 02:57:20 +0000 2009 # SIGALRM: Wed Sep 09 02:57:22 +0000 2009 # SIGALRM: Wed Sep 09 02:57:24 +0000 2009 # SIGALRM: Wed Sep 09 02:57:26 +0000 2009 # SIGALRM: Wed Sep 09 02:57:28 +0000 2009 # SIGALRM: Wed Sep 09 02:57:30 +0000 2009 # SIGALRM: Wed Sep 09 02:57:32 +0000 2009 # SIGALRM: Wed Sep 09 02:57:33 +0000 2009 # Wed Sep 09 02:57:33 +0000 2009