Created
January 20, 2012 16:25
-
-
Save JoshMcKin/1648242 to your computer and use it in GitHub Desktop.
Recurring Delayed Job 2.1 in Rails 3 without patching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Tested on DelayedJob 2.1 | |
class MyRecurringDelayedJob | |
def perform | |
# ...some slow code | |
end | |
def success(job) | |
MyRecurringDelayedJob.schedule_job(job) | |
end | |
# if you want to reschedule job on failure | |
def failure | |
MyRecurringDelayedJob.schedule_job | |
end | |
def self.time_to_recur | |
"#{(Date.today + 1.day).strftime('%Y-%m-%d')} 2:00:00".to_time | |
end | |
def self.queue_name | |
"MyRecurringDelayedJob" | |
end | |
def self.schedule_job(job=nil) | |
if job_exists?(job) | |
puts "#{queue_name} job is already scheduled for #{time_to_recur}." | |
else | |
Delayed::Job.enqueue new, :run_at => time_to_recur, :queue=> queue_name | |
puts "A new #{queue_name} job has been scheduled for #{time_to_recur}." | |
end | |
end | |
# If you want make sure a job recurs once per cycle, | |
# important if you have multiple DJ workers or App servers. | |
def self.job_exists?(job=nil) | |
conditions = ['queue = ? AND failed_at IS NULL', queue_name] | |
unless job.blank? | |
conditions[0] << " AND id != ?" | |
conditions << job.id | |
end | |
Delayed::Job.exists?(conditions) | |
end | |
end | |
# Use need to add the 'queue' column to your delayed jobs table. | |
# Add to an initializers to schedule first run | |
# if you have a DJ config initializer add it to the end of that. | |
MyRecurringDelayedJob.schedule_job | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment