Class: Async::Cron::Schedule::Generic

Inherits:
Object
  • Object
show all
Defined in:
lib/async/cron/schedule/generic.rb

Direct Known Subclasses

Daily, Hourly, Monthly, Periodic, Weekly

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(flags = Flags.new) ⇒ Generic

Returns a new instance of Generic.



15
16
17
# File 'lib/async/cron/schedule/generic.rb', line 15

def initialize(flags = Flags.new)
  @flags = flags
end

Instance Attribute Details

#flagsObject (readonly)

Returns the value of attribute flags.



19
20
21
# File 'lib/async/cron/schedule/generic.rb', line 19

def flags
  @flags
end

Instance Method Details

#increment(time = nil) ⇒ Object

Compute the next execution time after the given time.



22
23
24
# File 'lib/async/cron/schedule/generic.rb', line 22

def increment(time = nil)
  Time.now
end

#invoke(time) {|time| ... } ⇒ Object

Yields:

  • (time)


73
74
75
# File 'lib/async/cron/schedule/generic.rb', line 73

def invoke(time, &block)
  yield(time)
end

#run(time = Time.now, &block) ⇒ Object



67
68
69
70
71
# File 'lib/async/cron/schedule/generic.rb', line 67

def run(time = Time.now, &block)
  while true
    time = run_once(time, &block)
  end
end

#run_once(time = Time.now, &block) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/async/cron/schedule/generic.rb', line 26

def run_once(time = Time.now, &block)
  # The number of times the schedule has been dropped because the scheduled time was in the past:
  dropped = 0
  
  while true
    # Compute the next scheduled time:
    scheduled_time = increment(time)
    
    # If the time is not advancing and we are dropping, then raise an error:
    if scheduled_time <= time and dropped > 0
      raise RuntimeError, "Scheduled time is not advancing: #{scheduled_time} <= #{time}"
    end
    
    # Compute the delta until the next scheduled time:
    delta = scheduled_time.delta
    
    Console.debug(self, "Next scheduled time.", delta: delta, scheduled_time: scheduled_time, block: block)
    
    # If the time is in the past, and we are dropping, then skip this schedule and try again:
    if delta < 0 and @flags.drop?
      # This would normally occur if the user code took too long to execute, causing the next scheduled time to be in the past.
      Console.warn(self, "Skipping schedule because it is in the past.", delta: delta, scheduled_time: scheduled_time, block: block, dropped: dropped)
      dropped += 1
      next
    end
    
    break
  end
  
  Console.debug(self, "Waiting for next scheduled time.", delta: delta, scheduled_time: scheduled_time, block: block)
  sleep(delta) if delta > 0
  
  begin
    invoke(scheduled_time, &block)
  rescue => error
    Console::Event::Failure.for(error).emit(self, delta: delta, scheduled_time: scheduled_time, block: block)
  end
  
  return time
end