Friday, 21 November 2014

Adding a crontab in ubuntu by capistrano task using Rails Application

How ever in practice sometimes we required to add a cronjob while deployment of the rails application.here an example of replace an exiting or create a new crontab by capistrano task.have a look:

there are following steps to reached to the required result.these are:

1. Create a recipe named 'cron.rb' inside the 'config/recipes' folder.
2. Add the following code to that 'cron.rb'

namespace :crontab do
  desc "Install cronjobs"
  task :install, roles: :desired_role do
    template "crontab.erb", "/tmp/cronjob"
    run('crontab /tmp/cronjob')
  end
  after "deploy:cold", "crontab:install"
end

// if you are dealing with multiple servers and want to add crontab on only one server then add an extra role to that server/machine in 'config/environment.rb' like

server 'ip_of_the_server', :web, :app, :db, :role_for_cron, primary: true 
example:

server 'ip_of_the_server', :web, :app, :db, :cron, primary: true

modify 'cron.rb' like this:


namespace :crontab do
  desc "Install cronjobs"
  task :install, roles: :cron do
    template "crontab.erb", "/tmp/cronjob"
    run('crontab /tmp/cronjob')
  end
  after "deploy:cold", "crontab:install"
end


3. Create a template named 'crontab.erb' inside 'config/recipes/templates'.
// dont forget to require 'crontab.erb'  into your deploy.rb file.

4. Add cronjob into 'crontab.erb'.for this add the following code in 'crontab.erb'

* * * * * /bin/bash -l -c "cd <%= current_path %> && bundle exec rake_path task_namesapce:task_name RAILS_ENV=rails_env" >

example,

* * * * * /bin/bash -l -c "cd <%= current_path %> && bundle exec /home/<%= user %>/.rvm/rubies/ruby-2.1.2/bin/rake test_task:test RAILS_ENV=<%= rails_env %>" >> <%= current_path %>/crontab.txt

// this above cronjob will execute every minute every hour and when it execute add an entry to 'crontab.txt' file.

5. Customizing you cronjob execution delay:

you can customize your cronjob execute delay.as example:

*/5 * * * * // before cronjob will execute job every five minute 
delay.

 





No comments:

Post a Comment