[ rails ] delayed_job

Gemfile

gem 'delayed_job_active_record'

then

bundle install

run delay job in background on prod

Gemfile

gem 'daemons'

then

bundle install

config file

config/initializers/delayed_job.rb

Delayed::Worker.destroy_failed_jobs = false
Delayed::Worker.max_run_time = 30.minutes
Delayed::Worker.logger = Logger.new(Rails.root.join('log', 'delayed_job.log'))

app/jobs/newsletter_job.rb

NewsletterJob = Struct.new(:text, :emails) do
def perform
emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
end
end

or using class instead of **struct**

class NewsletterJob

attr_accessor :text, :emails

def initialize(text, emails)
@text = text
@emails = emails
end

def perform
emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
end

end

ref : https://www.leighhalliday.com/ruby-struct

Setup default queuename

NewsletterJob = Struct.new(:text, :emails) do
def perform
emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
end</pre>
def queue_name
'newsletter_queue'
end
end

This will be inserted in `delayed_jobs.queue` table column.

 

logging to log file in delayed_job 

make sure `Delayed::Worker.logger` is setup in the configuration file

Delayed::Worker.logger.debug("Log Entry")

ref : https://stackoverflow.com/questions/14631910/logging-in-delayed-job

 

Queue in rails console / or in rake task

Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.pluck(:email))

NOTE : this will insert into delayed_jobs table.

Run at specific time

Delayed::Job.enqueue(
NewsletterJob.new('lorem ipsum...', Customers.pluck(:email)), run_at: Time.zone.now.end_of_day
)

Run in realtime in the same thread within rspec

Delayed::Worker.new.work_off

NOTE : If you are trying to test for timing errors, race conditions, etc, this approach won’t help (since the jobs are processed in the same thread as RSpec).

 

List all delayed job in rails console

Delayed::Job.all

List by queue_name

Delayed::Job.where(queue: 'whatever_queue_name')

Check if job exists

Delayed::Job.where(queue: 'whatever_queue_name').present?

ref : https://github.com/collectiveidea/delayed_job,

https://stackoverflow.com/questions/3191900/delayed-job-not-processed-in-rspec,

http://blog.andolasoft.com/2013/04/4-simple-steps-to-implement-delayed-job-in-rails.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s