class MidgetJobs::Scheduler

Public Instance Methods

call() click to toggle source
# File lib/midget_jobs/scheduler.rb, line 3
def call
  Rails.logger.info "#{self.class.name} starting"
  @thread = Thread.new do
    Rails.logger.info "#{self.class.name} started and waiting for jobs"
    loop do
      sleep_till_next_job
      process_available_jobs
    end
  end
  @thread.abort_on_exception = true
  self
end
wakeup!() click to toggle source
# File lib/midget_jobs/scheduler.rb, line 16
def wakeup!
  Rails.logger.info "#{self.class.name}.#{__method__}"
  @thread.wakeup
end

Private Instance Methods

process_available_jobs() click to toggle source
# File lib/midget_jobs/scheduler.rb, line 23
def process_available_jobs
  MidgetJob.transaction do
    MidgetJob.for_processing.limit(Rails.configuration.x.midget_jobs.at_once).lock("FOR UPDATE SKIP LOCKED").each do |midget_job|
      Rails.logger.info "#{self.class.name} firing midget_job: #{midget_job.id} - #{midget_job.serialized['job_class']}"
      midget_job.fire_thread
      midget_job.destroy!
    end
  end
end
sleep_till_next_job() click to toggle source

interval till next job or 0 if there is no job - meaning sleep for ever or till wakeup

# File lib/midget_jobs/scheduler.rb, line 34
def sleep_till_next_job
  most_current = MidgetJob.order(run_at: :asc).first
  if most_current
    Rails.logger.info "#{self.class.name}.#{__method__} (#{[most_current.run_at.to_f - Time.current.to_f, 0.001].max} sec) till #{most_current.serialized['job_class']}"
    sleep [most_current.run_at.to_f - Time.current.to_f, 0.001].max
  else
    Rails.logger.info "#{self.class.name}.#{__method__}(Thread.stop)"
    Thread.stop
  end
end