Search code examples
ruby-on-railsrubycrondelayed-job

How to use Delayed Job to execute a method in a specific hour on Ruby on Rails?


I have this method:

module ApplicationHelper
  class AtualizarBanco

    require 'open-uri'
    require 'nokogiri'
    require 'net/http'

    def updatetable
      retorno = Net::HTTP.get_response(URI.parse('http://www.olx.com.br/loja/id/174483'))

      if retorno.code == "200"
        site = open ('http://www.olx.com.br/loja/id/174483')
        site_lido = site.read
        site_html = Nokogiri::HTML(site_lido)

        vetor_preco = site_html.at_css('#main-ad-list').css('.item').css('.OLXad-list-price').map{|q| q.text.sub!(" R$ ", "").sub!(".", "").to_f}
        vetor_texto = site_html.at_css('#main-ad-list').css('.item').css('.OLXad-list-title').map{|lista| lista.text.strip}
        vetor_catg = site_html.css('#main-ad-list .OLXad-list-line-2').xpath('p[@class="text detail-category"]').map{|q| q.children.first.text.strip}
        vetor_img = site_html.css('#main-ad-list .OLXad-list-image-box').xpath('span|img[@class="image"]/@src|img[@class="image lazy"]/@data-original').map(&:text)

        i = 0
        if ((vetor_preco.length == vetor_texto.length) && (vetor_preco.length == vetor_catg.length) && (vetor_preco.length == vetor_img.length))
          while i < vetor_preco.length
            @prod = Produto.new(nm_produto: vetor_texto[i], preco: vetor_preco[i], categoria: vetor_catg[i], img_produto: vetor_img[i])
            i += 1
            if (@prod.valid?)
              @prod.save
            end
          end
        end  
      end
    end

  end
end

And I want to execute this method everyday at 5:30 am GMT.

I did some searching, and I found out about the Delayed Job gem and the Cron scheduler, but it wasn't clear to me how I use them to do what I need.

Delayed Job works well on Rails 5.0.0.1 ? on the documentation it talks about versions 3.0+ and 4.2, it wasn't clear to me if it is "4.2 and above" or just 4.2.

I also don't know if I call the Delayed Job gem with just gem 'delayed-job' or if I need to use gem 'delayed_job_active_record', or if I need to change the config.active_job.queue_adapter.

On the documentation, it also doesn't say if the :run_at parameter accept specific time commands, in the examples it has only things like "5 minuts from now" or "2 hours from now".

Any help ?


Solution

  • You can use gem whenever, replace your method from application_helper to rake task updatetable.rake e.g.

    And your schedule will be as

    every 1.day, at: '5:30 am' do
      rake 'atualizar_banco:updatetable'
    end