Class: Delayed::Quota

Inherits:
Object
  • Object
show all
Defined in:
lib/delayed_job_memento/delayed/quota.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Quota

Returns a new instance of Quota.



8
9
10
11
12
13
14
# File 'lib/delayed_job_memento/delayed/quota.rb', line 8

def initialize(options)
  self.queue = options[:queue]
  self.interval = options[:interval]
  self.size = options[:size]
  self.started, self.reached = nil, nil
  self.instances[self.queue] = self
end

Instance Attribute Details

#intervalObject

Returns the value of attribute interval.



3
4
5
# File 'lib/delayed_job_memento/delayed/quota.rb', line 3

def interval
  @interval
end

#queueObject

Returns the value of attribute queue.



3
4
5
# File 'lib/delayed_job_memento/delayed/quota.rb', line 3

def queue
  @queue
end

#reachedObject

Returns the value of attribute reached.



3
4
5
# File 'lib/delayed_job_memento/delayed/quota.rb', line 3

def reached
  @reached
end

#sizeObject

Returns the value of attribute size.



3
4
5
# File 'lib/delayed_job_memento/delayed/quota.rb', line 3

def size
  @size
end

#startedObject

Returns the value of attribute started.



3
4
5
# File 'lib/delayed_job_memento/delayed/quota.rb', line 3

def started
  @started
end

Instance Method Details

#quota_reached?Boolean

fix class variables to instances

Returns:

  • (Boolean)


17
18
19
20
21
22
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
# File 'lib/delayed_job_memento/delayed/quota.rb', line 17

def quota_reached?
  current_time = Time.zone.now
  if self.reached != nil
    time_left = self.interval - (self.reached - self.started)
    if self.reached + time_left < current_time
      self.reached = nil
      self.started = current_time
      false
    else
      true
    end
  else
    if self.started != nil
      conditions = {
          queue: self.queue,
          created_at: self.started..current_time,
          locked_at: Time.new(0)..current_time
      }
      finished_jobs = Delayed::Memento.where(queue: self.queue,created_at: self.started..current_time,locked_at: Time.new(0)..current_time).count
      if finished_jobs >= self.size
        self.reached = current_time
        true
      else
        false
      end
    else
      self.started = current_time
      false
    end
  end
end

#rebalance_queueObject



49
50
51
52
53
54
55
56
57
# File 'lib/delayed_job_memento/delayed/quota.rb', line 49

def rebalance_queue
  run_at = self.interval - (self.reached - self.started)
  conditions = {queue: self.queue, locked_at: nil}
  Delayed::Job.where(conditions).find_in_batches(batch_size: self.size) do |batch|
    batch.each { |job| job.run_at = run_at }
    Delayed::Job.import batch, validate: false, on_duplicate_key_update: [:run_at]
    run_at= run_at + self.interval
  end
end