Gem to make to make jobs lockable. Useful when a job is called N times, but only a single execution is needed.
Add this line to your application's Gemfile:
gem 'activejob-lockable'
And then execute:
$ bundle
Or install it yourself as:
$ gem install activejob-lockable
Create an initializer with redis connection:
ActiveJob::Lockable.redis = Redis.current # if you have a redis instance
# or
ActiveJob::Lockable.redis = 'redis://localhost:6379/0'
# or
ActiveJob::Lockable.redis = {
host: '10.0.1.1',
port: 6380,
db: 15
}
# job
# nothing to change!
# code
MyJob.set(lock: 10.seconds).perform_later(id)
Now, after the first enqueue (perform_later), a lock will be created and the following enqueues within 10 seconds will be rejected.
A lock key by default:
job_name_in_downcase:md5(arguments)
To override the key you can override method lock_key
:
# job
def lock_key
'my-custom-key'
end
You can set a fixed lock_period
, in that case .set(lock: N)
will be ignored and the job will always be lockable:
# job
def lock_period
1.day
end
When a job is locked and another one is enqueued, you can set up a custom callback that will be called. This is useful if you want to raise exception or be notified:
# job
class MyJob < ApplicationJob
on_locked :raise_if_locked
def raise_if_locked
raise 'Job is locked'
end
end
Bug reports and pull requests are welcome on GitHub at qonto/activejob-lockable. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
The gem is available as open source under the terms of the MIT License.