Using Kiqit to Process the Existing Code to Background Process

Gem Sidekiq provides an easy way to move some long and lengthy time consuming processes to be moved to background and make user experience better. Simply add gem "sidekiq" to Gemfile, run bundle install and create some worker with the long lengthy code.

Before Sidekiq

tasks_controller.rb
1
2
3
4
5
6
7
8
9
class User < ActiveRecord::Base

  def some_time_consuming_task
    .....
    .....
    .....
  end

end

After Sidekiq

some_time_consuming_task_worker.rb
1
2
3
4
5
6
7
class SomeTimeConsumingTaskWorker
  def perform(user_id)
    user = User.find(user_id)
    .....
    .....
  end
end
tasks_controller.rb
1
2
3
4
5
6
7
class User < ActiveRecord::Base

  def some_time_consuming_task
    SomeTimeConsumingTaskWorker.perform_async(self.id)
  end

end

This way the task is moved to be processed in background. Looks pretty simple, cool and easy.

Wait !! , But what if I have a bunch of them in no of models ??

  1. Copy code from model to a new worker for every method.
  2. Remove code from the models.
  3. Copy code from model to a new worker for every method.

This does’t look like a good approach. Here, kiqit comes into the scenario and helps us to use the existing code without copy-pasting and creating new workers etc.

  1. Add gem “kiqit” to your rails Gemfile.
  2. Run bundle install
  3. Add the following line of code after some_time_consuming_task below the code …
tasks_controller.rb
1
2
3
4
5
6
7
8
9
10
class User < ActiveRecord::Base

  def some_time_consuming_task
    .....
    .....
    .....
  end
  later :some_time_consuming_task

end

That ways, everything is handled the same way, as we would have by creating workers explicitly.

Sources: Sidekiq and kiqit

Comments