From: ara.t.howard@... Date: 2006-06-08T03:49:24+09:00 Subject: Re: how do I impose a method call delay? On Thu, 8 Jun 2006, Jason Sallis wrote: > I've got a simple Ruby class that has one method which uses open-uri to pass > a request to a remote server and retrieve an xml document containing some > server statistics. Nothing too exciting and it's working fine. The > administrator has asked that we limit our calls to once every 30 seconds to > avoid hammering the server. I'd like to bake this forced delay right into > my class so that if another application is using it and tries to make 2 > calls within 30 seconds, the second call is delayed until the 30 second time > period is up. Any ideas on how I could approach this? here's an idea for a thread-safe impl: harp:~ > cat a.rb #! /usr/bin/env ruby require 'sync' module Delay module ClassMethods def delay m, t m, t = m.to_s, t.to_f dm = "__delayed_#{ m }__" module_eval <<-code alias_method "#{ dm }", "#{ m }" def #{ m }(*a, &b) __delay_init__ __delay__("#{ m }"){ #{ dm }(*a, &b) } end code __delay_time__[m] = t end def __delay_last__() @__delay_last__ ||= {} end def __delay_time__() @__delay_time__ ||= Hash.new{|h,k| h[k] = 0.0} end end module InstanceMethods def __delay_last__() self.class.__delay_last__ end def __delay_time__() self.class.__delay_time__ end def __delay_init__() extend Sync_m unless Sync_m === self end def __delay__ m m = m.to_s synchronize do last, now = __delay_last__[m], Time.now if last already = now.to_f - last.to_f t = __delay_time__[m] - already sleep t if t > 0 end __delay_last__[m] = Time.now yield end end end def self.included other other.extend ClassMethods other.module_eval{ include InstanceMethods } end end class C include Delay def foo STDOUT.sync = true puts "#{ Thread.current.object_id } : #{ Time.now }" end delay 'foo', 2 end c = C.new t1 = Thread.new { 2.times{ c.foo } } t2 = Thread.new { 2.times{ c.foo } } t1.join t2.join harp:~ > ruby a.rb -609340922 : Wed Jun 07 12:48:22 MDT 2006 -609341842 : Wed Jun 07 12:48:24 MDT 2006 -609340922 : Wed Jun 07 12:48:26 MDT 2006 -609341842 : Wed Jun 07 12:48:28 MDT 2006 regards. -a -- suffering increases your inner strength. also, the wishing for suffering makes the suffering disappear. - h.h. the 14th dali lama