Skip to content

Instantly share code, notes, and snippets.

@dblock
Created August 16, 2012 13:21
Show Gist options
  • Save dblock/3370052 to your computer and use it in GitHub Desktop.
Save dblock/3370052 to your computer and use it in GitHub Desktop.
A mongoid delayed job observer, used in test environment to kick off any delayed jobs as they are queued.
class DelayedJobObserver < Mongoid::Observer
observe Delayed::Job
class << self
attr_accessor :total_processed
attr_accessor :total_errors
attr_accessor :enabled
def enabled?
!! DelayedJobObserver.enabled
end
def enable!
DelayedJobObserver.enabled = true
end
def disable!
DelayedJobObserver.enabled = false
end
def reset!
DelayedJobObserver.total_processed = 0
DelayedJobObserver.total_errors = 0
DelayedJobObserver.enable!
end
end
def after_create(delayed_job)
begin
delayed_job.invoke_job if DelayedJobObserver.enabled?
rescue
DelayedJobObserver.total_errors += 1
end
DelayedJobObserver.total_processed += 1
end
end
DelayedJobObserver.reset!
@dblock
Copy link
Author

dblock commented Nov 2, 2015

Note that this is now obsolete.

In 4.1.0 they allowed Delayed::Worker.delay_jobs to be a proc, see collectiveidea/delayed_job@ce88693.

Now, whenever a job is being delayed, they do this:

Delayed::Worker.delay_job?(job) ? job.save : job.invoke_job

Our version now selects what to do in specs based on when the job is to run.

Delayed::Worker.delay_jobs = ->(job) {
  job.run_at && job.run_at > Time.now.utc
}

@valer-cara
Copy link

Minor link update:

Now, whenever a job is being delayed, they do this

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