Class: IntervalExec
- Inherits:
-
Object
- Object
- IntervalExec
- Defined in:
- lib/interval_exec/interval_exec.rb
Class Method Summary collapse
-
.run(duration, overrun_handler, opts = {}, &block) ⇒ Object
Loops a block of code, handling execution interval as specified by duration and params.
Class Method Details
.run(duration, overrun_handler, opts = {}, &block) ⇒ Object
Loops a block of code, handling execution interval as specified by duration and params.
Params:
duration-
Execution interval in seconds
overrun_handler-
Defines what should happen when the block execution exceeds duration
Possible overrun_handler values:
:immediate-
If execution exceeds duration, next interval begins immediately after long cycle completes.
:fixed-
Next interval begins exactly duration seconds after execution completes.
:next-
Execution skips a cycle, and picks up at next scheduled interval. For example, if cycle is 10s and code execution takes 15s, IntervalExec will sleep for 5s so execution begins at 20s mark.
Options:
:interval_end_proc-
A proc to be called at the end of every interval with one parameter:
actual_duration, block execution time in seconds
Notes:
-
If code execution ends early, code sleeps until duration is reached.
-
Code runs inside a standard
loop, sobreakandnextkeywords can be used to stop execution and skip to next interval -
IntervalExec doesn’t do any exception handling
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/interval_exec/interval_exec.rb', line 23 def self.run(duration, overrun_handler, opts = {}, &block) interval_end_proc = opts[:interval_end_proc] loop do start_time = Time.now yield end_time = Time.now actual_duration = end_time - start_time if actual_duration < duration Kernel.sleep(duration - actual_duration) else case overrun_handler when :fixed Kernel.sleep(duration) when :next overrun = actual_duration % duration Kernel.sleep(duration - overrun) end end interval_end_proc.call(actual_duration) unless interval_end_proc.nil? end end |