Saturday 13 April 2013

Rails Task: Creation and deployment

Rails does have one very interesting module, besides dozens of other : RAKE

Rake help you write task and then you can use it to write schedulers or database maintenance script or anything, as per your requirement.
I used it to write one cron job.
Here is how i made one rake task.

$ rails generate task   namespace_name taskName_one taskName_two
 ==> It will generate file with the name  namespace_name.rake and in there it will define two methods
with the name "taskName_one" and "taskName_two".



namespace :namespace_name do
   desc "taskName_one description"
   task :taskName_one => :environment do
    // Your custome code
   end


   desc "taskName_two description"
   task :taskName_two=> :environment do
    // YOur custom code
   end
end

In the task block, you may add your custom code.It could be updating database related task or whatever.

Run task:
   To run you task, use this command:
 $ rake namespace:task_name
  To get task description only
 $ rake -t namespace:task_name


Deployment on Heroku platform:

  1. Deploy your app on heroku
  2. Get scheduler:addon insalled : https://addons.heroku.com/scheduler
    1. Go to app control panel and after selecting the application, click the "get add-on" button
    2. Find 'free' herku-scheduler add-onn and add it to your selected application
    3. OR simply type "$ heroku addons:open scheduler" on your terminal.
  3. To run task on heroku
      $ heroku run rake  namespace:task_name
  4. To add cron job.
    1. Go to scheduler addon-on setting page.
      : write  "rake  namespace:taskName " and set the schedule.
    2. That's, it. Your task is up and running.
      Heroku Scheduler: Adding a task


NOTE:  "=> :environment" :  This tells task to inherit everything from environment.It also include your model and controllers. You may use your model as you uses in your controller.


  1.  To include your custom script
         => require Rails.root.join('app', 'path', 'to', 'yout',  'script.rb')
  2. To include ruby gem
               => require "your_gem"      eg.  require "nokogiri"             Do as you normally do in your script

References: 
  1. https://devcenter.heroku.com/articles/scheduler
  2.  https://heroku-scheduler.herokuapp.com/dashboard


No comments:

Post a Comment