84

At the moment, I have a sidekiq job like this:

class SyncUser
  include Sidekiq::Worker

  def perform(user_id)
    #do stuff
  end
end

I am placing a job on the queue like this:

SyncUser.perform_async user.id

This all works of course but there is a bit of a lag between calling perform_async and the job actually getting executed.

Is there anything else I can do to tell sidekiq to execute the job immediately?

dagda1
  • 26,856
  • 59
  • 237
  • 450
  • 3
    the whole idea of using sidekiq is to perform things async. If you would like to execute it directly, make sure you have enough workers available, or execute it within the request itself. – jewilmeer Oct 08 '13 at 16:02

3 Answers3

157

There are two questions here.

If you want to execute a job immediately, in the current context you can use:

SyncUser.new.perform(user.id)

If you want to decrease the delay between asynchronous work being scheduled and when it's executed in the sidekiq worker, you can decrease the poll_interval setting:

Sidekiq.configure_server do |config|
  config.poll_interval = 2
end

The poll_interval is the delay within worker backends of how frequently workers check for jobs on the queue. The average time between a job being scheduled and executed with a free worker will be poll_interval / 2.

Winfield
  • 18,985
  • 3
  • 52
  • 65
  • 8
    In case anyone's wondering, the default poll_interval is currently 15s. https://github.com/mperham/sidekiq/wiki/Scheduled-Jobs#checking-for-new-jobs – Bryce Johnson Oct 20 '16 at 15:17
  • 3
    Are there any drawbacks to this? Could this mess with concurrency? – barnacle.m Apr 26 '18 at 11:03
  • 1
    Sidekiq's use of Redis lists and atomic operations are great for concurrency. The length of the polling interval will not effect concurrency but it will effect the amount of load on the redis server used for the sidekiq queue. A longer poll interval means less frequent polling for new jobs on the queue but jobs spending more time in the queue. A shorter polling interval means less time in the queue, but more frequent/higher volume of polling from your sidekiq servers. – Winfield Apr 26 '18 at 15:08
  • 3
    Updating @BryceJohnson since Sidekiq 5.1 the default is 5s. – Ray Baxter Mar 23 '22 at 15:37
4

use .perform_inline

SyncUser.perform_inline(user.id)

or even in your production console:

require 'sidekiq/testing'
Sidekiq::Testing.inline!

SyncUser.perform_inline(user.id)
itsnikolay
  • 17,415
  • 4
  • 65
  • 64
-3

For those who are using Sidekiq via the Active Job framework, you can do

SyncUser.perform_now(user.id)
Dennis
  • 56,821
  • 26
  • 143
  • 139
Daniel Morris
  • 6,852
  • 8
  • 25
  • 30
  • 2
    This answer is incorrect. Notice the question has: `include Sidekiq::Worker` instead of inheriting from `ActiveJob::Base`. – Brendan Benson Aug 04 '20 at 05:14