Sha256: 35aa896810cdbee2a202faf9dcee832a2c4ab825dccb3c9a34fae8107321071a

Contents?: true

Size: 1.22 KB

Versions: 7

Compression:

Stored size: 1.22 KB

Contents

require 'with_advisory_lock'

class Roqua::Scheduling::Scheduler
  def ping
    with_advisory_lock do
      jobs_to_run.each do |cron_job|
        begin
          run_task cron_job
        rescue Exception => ex
          Roqua::Support::Errors.report(ex)
          raise ex if Rails.env.test?
        end
      end

      Appsignal.increment_counter("scheduler.completed", 1)
    end
  end

  def jobs_to_run
    Roqua::Scheduling::CronJob.where('next_run_at <= ?', Time.now)
  end

  def tasks
    schedule.tasks
  end

  def schedule
    Roqua::Scheduling::Schedule.current_schedule
  end

  def advisory_lock_name
    db_name = ActiveRecord::Base.respond_to?(:connection_db_config) \
              ? ActiveRecord::Base.connection_db_config.database
              : ActiveRecord::Base.connection_config[:database]
    "#{db_name}_cron_lock"
  end

  private

  def with_advisory_lock
    ActiveRecord::Base.with_advisory_lock(advisory_lock_name, timeout_seconds: 0) do
      yield
    end
  end

  def run_task(cron_job)
    task = schedule.tasks[cron_job.name]
    task.run

    Appsignal.increment_counter("scheduler.run_task.completed", 1, task_name: task.name)
    cron_job.update completed_at: Time.now, next_run_at: task.next_run_at
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
roqua-support-0.4.6 lib/roqua/scheduling/scheduler.rb
roqua-support-0.4.5 lib/roqua/scheduling/scheduler.rb
roqua-support-0.4.4 lib/roqua/scheduling/scheduler.rb
roqua-support-0.4.3 lib/roqua/scheduling/scheduler.rb
roqua-support-0.4.2 lib/roqua/scheduling/scheduler.rb
roqua-support-0.4.1 lib/roqua/scheduling/scheduler.rb
roqua-support-0.4.0 lib/roqua/scheduling/scheduler.rb