Wednesday, August 26, 2015

How to schedule tasks in Ruby on Rails

There are some scenarios where we would like to set some actions to be performed at certain times of the day, or periodically. There is an easy way set up these cron jobs in Ruby on Rails with rufus-scheduler.



It does support four kinds of scheduling:
scheduler.in '10d' do
    # do something in 10 days
end
scheduler.at '2030/12/12 23:30:00' do
    # do something at a given point in time
end
scheduler.every '3h' do
    # do something every 3 hours
end
scheduler.cron '5 0 * * *' do
    # do something every day, five minutes after midnight
end
The integration is incredibly simple. Just create a new file task_scheduler.rb in your /config/initializers folder, include the gem rufus/scheduler and set up your task. In the example below, I am sending an HTTP GET request to Google every 2 minutes and print the status code.
# Required Gems
require 'rubygems'
require 'rufus/scheduler'
require 'net/https'
require 'uri'
# Initialize the scheduler
scheduler = Rufus::Scheduler.new
# Action to be performed every 2 minutes
scheduler.every("2m") do
    # Send a GET request to Google and print the response code
    uri = URI.parse("http://www.google.com")
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri)
    response = http.request(request)
    puts response.code
end

No comments:

Post a Comment