Delayed extensions

Mike Perham edited this page Apr 28, 2017 · 43 revisions

Delayed extensions provide a very easy and simple way to make method calls asynchronous. By default, all class methods and ActionMailer deliveries can be performed asynchronously.

They are disabled by default in Sidekiq 5+. Use Sidekiq::Extensions.enable_delay! to turn them on.

ActionMailer

Use delay to deliver your emails asynchronously. Use delay_for(interval) or delay_until(time) 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)
UserMailer.delay_until(5.days.from_now).find_more_friends_email(@user.id)

It is recommended to avoid passing an object instance to mailer methods. Instead, pass an object id and then re-instantiate the object in the mailer method, per Best Practices.

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

ActiveRecord

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

User.delay.delete_old_users('some', 'params')
User.delay_for(2.weeks).whatever
User.delay_until(2.weeks.from_now).whatever

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

Class Methods

Any class method can be delayed via the same methods as above:

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

Just remember to keep the method arguments simple, don't pass complex Ruby objects.

Advanced Options

You can tune the options used with a .delay call by passing in options:

MyClass.delay(:retry => false).some_method(1, 2, 3)
MyClass.delay(:queue => 'low').some_method(1, 2, 3)
MyClass.delay_for(10.minutes, :retry => false).some_method(1, 2, 3)

Notes

The extensions have two drawbacks:

  • they use YAML to serialize arguments so the job payload can become very large easily if passing complex Ruby objects.
  • they add methods to Class

For these reasons, they are disabled by default.

Previous: Scheduled Jobs Next: Deployment