简体   繁体   English

我如何使用rufus-scheduler和Rails 4调用动态调度程序来调用一天中多次获取推文的方法

[英]how can i call a dynamic scheduler to call a method to get tweets several times in a day with rufus-scheduler and Rails 4

I need to call tweeter api in a day with fixed time like 1PM, 3PM, 9AM.. I am using twiter gem and rufus-scheduler 我需要在固定时间的一天(例如1 PM、3PM、9AM)中调用tweeter api。我正在使用twiter gem和rufus-scheduler

Here is my model 这是我的模特

class Feed < ActiveRecord::Base

  def self.latest
    order('created_at desc').take(500)
  end

  def self.pull_tweets
    $client.search("#ukraine", since_id: maximum(:tweet_id), count: 10).take(10).each do |tweet|

      create!(
        tweet_id: tweet.id,
        content: tweet.text,
        screen_name: tweet.user.screen_name,
        )

     end
 end

end

Here is the controller where i am using the scheduler to call pull_tweets 这是我使用调度程序调用pull_tweets的控制器

class FeedsController < ApplicationController

  def index

    scheduler = Rufus::Scheduler.new
    scheduler.schedule_every('60s') do
      Feed.pull_tweets
    end
   @tweets = Feed.latest
 end
end

Its working perfectly but how i can set multiple times like 1AM, 3PM, 9AM for scheduling the task from users input? 它的工作原理完美,但是我如何可以设置多次(如1 AM、3PM、9AM)以通过用户输入来安排任务?

Simplify your controller to: 将控制器简化为:

class FeedsController < ApplicationController
  def index
    @tweets = Feed.latest
  end
end

Then make sure you have a config/initializers/scheduler.rb that looks like: 然后确保您有一个config / initializers / scheduler.rb看起来像:

require 'rufus-scheduler'

Rufus::Scheduler.singleton.every('60s') { Feed.pull_tweets }

So that you have a single scheduler for the whole Ruby process. 这样您就可以为整个Ruby流程设置一个调度程序。

To answer your question: 要回答您的问题:

require 'rufus-scheduler'

Rufus::Scheduler.singleton.cron('0 1,9,15 * * *') { Feed.pull_tweets }
  # pull tweets at 0100, 0900 and 1500

Your code is creating a rufus-scheduler instance each time a browser GETs /feeds, the code here has a single scheduler. 每当浏览器GET / feeds时,您的代码都会创建一个rufus-scheduler实例,此处的代码只有一个调度程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM