Skip to content

Delayed extensions

mperham edited this page Aug 30, 2012 · 52 revisions

Sidekiq includes a similar feature to DelayedJob which allows you to make ActiveRecord method calls and ActionMailer deliveries asynchronous.

ActionMailer

Use delay to deliver your emails asynchronously. Use delay_for(interval) to deliver the email at some point in the future.

UserMailer.delay.welcome_email(@user.id)
UserMailer.delay_for(5.days).find_more_friends_email(@user.id)

You can also easily extend the devise gem to send emails using sidekiq.

ActiveRecord

Use delay or delay_for(interval) to asynchronously execute arbitrary methods on your ActiveRecord instance or classes.

User.delay.delete_old_users('some', 'params')
@user.delay.update_orders(1, 2, 3)
User.delay_for(2.weeks).whatever

I strongly recommend avoid delaying methods on instances. This stores object state in Redis and which can get out of date, causing stale data problems.

Class Methods

Any class method can be delayed:

MyClass.delay.some_method(1, 'bob', true)

Sidekiq::Worker

Use perform_in(time, *args) to schedule worker job execution at some point in the future.

class OffersGeneratorWorker
  include Sidekiq::Worker
  def perform(quote_id)
    ...
  end
end

OffersGeneratorWorker.perform_in(1.hour, quote.id)

Troubleshooting

The psych engine is the only supported YAML engine. This is the default engine in Ruby 1.9. If you see a YAML dump/load stack trace, make sure syck is not listed.

Objects which contain Procs can be dumped but cannot be loaded by Psych. This can happen with ActiveRecord models that use the Paperclip gem. IMO this is a Ruby bug.

o = Object.new
o.instance_variable_set :@foo, Proc.new { 'hello world' }
yml = YAML.dump(o) # works!
YAML.load(yml) # BOOM

Clone this wiki locally