Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Workers in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 985
    Comment on it

    Sometimes to improve the performance of application we need to schedule some slow tasks into background, that is where Workers comes in the picture. So instead of executing slow tasks during the HTTP request execute them into background.


    In Rails to move long-running jobs in a background process we have many solutions available and one of them is Sidekiq.    
    Sidekiq is a Ruby's background processing library. It has some methods which make background processing quite simple.
    Sidekiq uses Redis to maintain a job queue so first install that.    
    When the Redis installation is done, add gem "sidekiq" to your Gemfile and run bundle.
    Once the Sidekiq gem is installed, start sidekiq by running bundle exec sidekiq.
    The process to use it is simply first create a separate worker class and we’ll do this, creating a class in a new app/workers directory. Putting it here ensures that it’s auto-loaded by the application.


    So first we create a new class in app/workers directory.So that it will be auto-loaded by the application.
    here we are creating a background worker in # app/workers/project_cleanup_worker.rb

    class ProjectCleanupWorker
      include Sidekiq::Worker
    
      def perform(project_id)
        # do lots of project cleanup stuff here
      end
    end

    Calling the Worker here
     

    ProjectCleanupWorker.perform_async(@project.id)

    rather then calling perform_async on a worker we can call "perform_in" and give a duration. A job will not then start to be processed until that time has passed.

    ProjectCleanupWorker.perform_in(1.hour, @project.id)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: