Skip to content

Instantly share code, notes, and snippets.

@cainlevy
Created May 16, 2014 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cainlevy/c6cfa67d44fe7427dea6 to your computer and use it in GitHub Desktop.
Save cainlevy/c6cfa67d44fe7427dea6 to your computer and use it in GitHub Desktop.
Monkey-patch for Delayed::Job's MySQL reserve strategy
require 'delayed_job_active_record'
module Delayed
module Backend
module ActiveRecord
class Job
# override UPDATE..LIMIT strategy
# see https://github.com/collectiveidea/delayed_job_active_record/issues/63#issuecomment-26284690
def self.reserve(worker, max_run_time = Worker.max_run_time)
ready_scope = self.ready_to_run(worker.name, max_run_time)
ready_scope = ready_scope.where('priority >= ?', Worker.min_priority) if Worker.min_priority
ready_scope = ready_scope.where('priority <= ?', Worker.max_priority) if Worker.max_priority
ready_scope = ready_scope.where(:queue => Worker.queues) if Worker.queues.any?
ready_scope = ready_scope.by_priority
now = self.db_time_now
ready_scope.limit(worker.read_ahead).detect do |job|
count = ready_scope.where(:id => job.id).update_all(:locked_at => now, :locked_by => worker.name)
count == 1 && job.reload
end
end
end
end
end
end
@csmuc
Copy link

csmuc commented Aug 18, 2014

May I promote collectiveidea/delayed_job_active_record#89, which would make things a bit easier

@maletor
Copy link

maletor commented Aug 20, 2014

And if you just want to use the default method:

module Delayed
  module Backend
    module ActiveRecord
      class Job
        class << self
          alias_method :reserve_with_scope, :reserve_with_scope_using_default_sql
        end
      end
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment