我试图使用控制器中的rufus调度gem来每分钟从api中提取最低价格

时间:2017-01-15 21:19:37

标签: ruby-on-rails api model-view-controller scheduler

这是我的初始化程序,适用于每5,10,20等秒提取所有最低价格和平均价格

    unless defined?(Rails::Console) || File.split($0).last == 'rake'
 s = Rufus::Scheduler.singleton
 s.every '10m' do
   Rails.logger.info "hello, it's {Time.now}"
   Rails.logger.flush
   Bid.all.each do |bid|
     id = bid.event_id
    @events = Unirest.get("https://api.seatgeek.com/2/events/#{id}?&client_id=NjQwNTEzMXwxNDgxNDkxODI1").body
    if @events["stats"]
      @low = @events["stats"]["lowest_price"] || 0
      @avg = @events["stats"]["average_price"] || 0
      BuyNowBid.create(bid_id: bid.id, lowest_price: @low , average_price: @avg)
    end
  end 
end
end

但是当我尝试从控制器创建出价然后尝试从api中取出最低和平均价格时,它已经开始工作几个小时了,现在任何提示都会非常感激

    def create 
#@bid?
#seatgeek id 
@bidd = Bid.new(event_id: params[:event_id], user_id: session[:user_id], bid: params[:bid], lowest_price: params[:lowest_price])    
if session[:user_id] == current_user.id
  @bidd.save
  @events = Unirest.get("https://api.seatgeek.com/2/events/#{@bidd.event_id}?&client_id=NjQwNTEzMXwxNDgxNDkxODI1").body
  if @events["stats"]
    @low = @events["stats"]["lowest_price"] || 0
    @avg = @events["stats"]["average_price"] || 0
    BuyNowBid.create(bid_id: @bidd.id, lowest_price: @low , average_price: @avg)
  end

  Rufus::Scheduler.singleton.every '10s' do
    @events = Unirest.get("https://api.seatgeek.com/2/events/#{@bidd.event_id}?&client_id=NjQwNTEzMXwxNDgxNDkxODI1").body
    if @events["stats"]
      @low = @events["stats"]["lowest_price"] || 0
      @avg = @events["stats"]["average_price"] || 0
      BuyNowBid.create(bid_id: @bidd.id, lowest_price: @low , average_price: @avg)
    end
  end
  flash[:success] = "bid created."
  redirect_to "/users/#{current_user.id}"
else
  flash[:warning] = 'please sign in'
  redirect_to '/login'
end
end

1 个答案:

答案 0 :(得分:0)

我找到了一种方法,通过阅读更多的rufus文档并修补它一段时间。我能够创建一个在初始化程序中访问rufus调度程序的方法。

    def restart_jobs
puts 'Stopping rufus'
Rufus::Scheduler.singleton.jobs(:tag => 'main_process').each do |job|
 Rufus::Scheduler.singleton.unschedule(job)
end
puts 'Starting rufus'
load "#{Rails.root}/config/initializers/scheduler.rb"

端   结束 并且在创建出价后调用重启作业方法,以便用户刚创建的出价在开始备份时添加到调度程序

    def create 
@bidd = Bid.new(event_id: params[:event_id], user_id: session[:user_id], bid: params[:bid], lowest_price: params[:lowest_price])    
if session[:user_id] == current_user.id
  @bidd.save
  send_message("+13125501444", "test")
  restart_jobs
  flash[:success] = "bid created."
  redirect_to "/users/#{current_user.id}"
else
  flash[:warning] = 'please sign in'
  redirect_to '/login'
end
end

我在inativeizer的调度程序中更改的唯一部分是添加哈希

    :tag => 'main_process'

这里是调度程序

    unless defined?(Rails::Console) || File.split($0).last == 'rake'
 s = Rufus::Scheduler.singleton
 s.every '1m', :tag => 'main_process' do
   Rails.logger.info "hello, it's #{Time.now}"
   Rails.logger.flush