Skip to content

Instantly share code, notes, and snippets.

@glaucocustodio
Last active September 15, 2023 20:33
Show Gist options
  • Save glaucocustodio/47b255644ab9ef8e9cec15fd4792968c to your computer and use it in GitHub Desktop.
Save glaucocustodio/47b255644ab9ef8e9cec15fd4792968c to your computer and use it in GitHub Desktop.
ActiveJob debouncer
# app/jobs/job_debouncer.rb
module JobDebouncer
extend ActiveSupport::Concern
class_methods do
def perform_later_once(*args, wait_time: 15.seconds)
job_key = "job_debouncer_#{self}_#{args}"
return if Rails.cache.exist?(job_key)
Rails.cache.write(job_key, 1, expires_in: wait_time)
set(wait: wait_time).perform_later(*args)
end
def perform_later_once_in_minutes(*args)
perform_later_once(args, wait_time: 2.minutes)
end
end
end
# app/jobs/user_destroyer_job.rb
class UserDestroyerJob < ApplicationJob
queue_as :default
include JobDebouncer
def perform(user)
user.destroy!
end
end
# any file
UserDestroyerJob.perform_later_once(User.last)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment