Sha256: 8446bd28567c4039368622d468fc96a462d95cf102abfdc104d056f390a48740

Contents?: true

Size: 1.73 KB

Versions: 6

Compression:

Stored size: 1.73 KB

Contents

require "active_support/concern"

module RocketJob
  module Plugins
    module Job
      # Throttle the number of jobs of a specific class that are processed at the same time.
      #
      # Example:
      #   class MyJob < RocketJob::Job
      #     # Maximum number of jobs of this class to process at the same time.
      #     self.throttle_running_jobs = 25
      #
      #     def perform
      #       # ....
      #     end
      #   end
      #
      # Notes:
      # - The number of running jobs will not exceed this value.
      # - It may appear that a job is running briefly over this limit, but then is immediately back into queued state.
      #   This is expected behavior and is part of the check to ensure this value is not exceeded.
      #   The worker grabs the job and only then verifies the throttle, this is to prevent any other worker
      #   from attempting to grab the job, which would have exceeded the throttle.
      module ThrottleRunningJobs
        extend ActiveSupport::Concern

        included do
          # Limit number of jobs running of this class.
          class_attribute :throttle_running_jobs
          self.throttle_running_jobs = nil

          define_throttle :throttle_running_jobs_exceeded?
        end

        private

        # Returns [Boolean] whether the throttle for this job has been exceeded
        def throttle_running_jobs_exceeded?
          return unless throttle_running_jobs&.positive?

          # Cannot use this class since it will include instances of parent job classes.
          RocketJob::Job.with(read: {mode: :primary}) do |conn|
            conn.running.where("_type" => self.class.name, :id.ne => id).count >= throttle_running_jobs
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rocketjob-5.4.0.beta2 lib/rocket_job/plugins/job/throttle_running_jobs.rb
rocketjob-5.4.0.beta1 lib/rocket_job/plugins/job/throttle_running_jobs.rb
rocketjob-5.3.3 lib/rocket_job/plugins/job/throttle_running_jobs.rb
rocketjob-5.3.2 lib/rocket_job/plugins/job/throttle_running_jobs.rb
rocketjob-5.3.1 lib/rocket_job/plugins/job/throttle_running_jobs.rb
rocketjob-5.3.0 lib/rocket_job/plugins/job/throttle_running_jobs.rb