Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Background job using whenever gem rails

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 682
    Comment on it

    Whenever gem is used to easily schedule tasks using cron jobs, it enables you to manipulate standard functionality of your machine using Ruby code.

    1: To start with Whenever we have to install gem

     gem install whenever     # insert this line in your gemfile. 
     bundle install                 # run 'bundle install' command.
    

    2: Secondly we have to wheneverize our application with command given below-:

     wheneverize .
    

    this command will create schedule.rb file in our config folder of rails app, we will use this file to manage our schedule/automated tasks.

    3: Create rake task

      namespace :on_line_off_line do
          desc "Checking online offline participants"
          task check: :environment do
            SessionParticipant.check_participant_is_online      #Model.method
         end
      end
    

    4: After we set up our rake task, we need to use Whenever to schedule our task and we can do it by writing below code in schedule.rb file.

    every 1.minute do         #this will run my task in every one minute...
     command "echo 'Cron job started......'"
     rake "on_line_off_line:check"
    end
    

    5: We can also insert logs in any file by inserting following code in schedule.rb.

     (set :output, "../rails_project_folder/file.log")   # file path where we want to save logs...
    

    6: We have almost done every thing to run background job, we just have to update system's cron tab file using following command ...

    $whenever -i    # command to update cron tab file.
    $whenever -l        # command to reload cron tab file data.
    $whenever -c      # command to clear cron tab file data.
    

    That's it, enjoy... :)

 1 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: