Class: Object
- Inherits:
- BasicObject
- Defined in:
- lib/once_in.rb
Instance Method Summary collapse
-
#once_in(period, level = 0, scope = :global) ⇒ Object
Runs block once every ‘period` seconds.
Instance Method Details
#once_in(period, level = 0, scope = :global) ⇒ Object
Runs block once every ‘period` seconds
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/once_in.rb', line 9 def once_in period, level = 0, scope = :global # once per this key key = Kernel.caller[level] # find out last execution time last = case scope when :global (@@once_in_last_times ||= {})[key] when :thread (Thread.current[:once_in_last_times] ||= {})[key] else raise "invlid scope #{scope.inspect}. valid scopes are :global and :thread" end now = Time.now.utc skip = last && (now - last ) # run again if we didn't run yet, or we did it long time ago if !last || (now - last > period) if :global == scope @@once_in_last_times[key] = now else Thread.current[:once_in_last_times][key] = now end yield end end |