Rails 5 个应用 运行 后台任务

Rails 5 app running background tasks

我构建了一个小型 rails 应用程序,并有一个 ruby 脚本,我想 运行 在我的应用程序后台运行。目前这段代码放在我的lib目录下(lib/tweetstreamer.rb)。在让代码在后台继续 运行 的同时完成此任务的最简单方法是什么?我需要在我的应用程序控制器中使用某种类型的命令吗?我发现当我使用 "rails runner path/to/tweetstreamer.rb" 时,我的脚本 运行 非常完美。

tweetstreamer.rb可以看下面

require 'tweetstream'
require 'twitter'
require 'mixpanel-ruby'

  TweetStream.configure do |conf|
  conf.consumer_key = "XXXXXXX"
  conf.consumer_secret = "XXXXXXX"
  conf.oauth_token = "XXXXXXX"
  conf.oauth_token_secret = "XXXXXXX"
  conf.auth_method = :oauth
  end

  @store_account = Twitter::REST::Client.new do |config|
  config.consumer_key = "XXXXXXX"
  config.consumer_secret = "XXXXXXX"
  config.access_token = "XXXXXXX"
  config.access_token_secret = "XXXXXXX"
  end

  client = TweetStream::Client.new

  client.track('mysampletweet') do |status|

  msg = status.text
  tag = "#mysampletweet"

  puts msg
  puts tag

  if msg.include? tag
  message = "@#{status.user.screen_name} Happy Holidays from @myaccountname!"
  sleep 5
  @store_account.update(message, in_reply_to_status_id: status.id)
  end

  @tracker = Mixpanel::Tracker.new("XXXXXXX")

  @tracker.track(status.id, 'Tweets Received', { 'Hashtag' => tag, 'Message' => msg })

  puts 'Your code ran'
  end

您可以将其设为抽佣任务。将命名空间 myappname 更改为您的应用程序的名称。

保存在 myappname/lib/tasks/tweetstream.rake:

namespace :myappname do
  task :tweetstream => :environment do

    require 'tweetstream'
    require 'twitter'
    require 'mixpanel-ruby'

    TweetStream.configure do |conf|
    conf.consumer_key = "XXXXXXX"
    conf.consumer_secret = "XXXXXXX"
    conf.oauth_token = "XXXXXXX"
    conf.oauth_token_secret = "XXXXXXX"
    conf.auth_method = :oauth
    end

    @store_account = Twitter::REST::Client.new do |config|
    config.consumer_key = "XXXXXXX"
    config.consumer_secret = "XXXXXXX"
    config.access_token = "XXXXXXX"
    config.access_token_secret = "XXXXXXX"
    end

    client = TweetStream::Client.new

    client.track('mysampletweet') do |status|

    msg = status.text
    tag = "#mysampletweet"

    puts msg
    puts tag

    if msg.include? tag
    message = "@#{status.user.screen_name} Happy Holidays from @myaccountname!"
    sleep 5
    @store_account.update(message, in_reply_to_status_id: status.id)
    end

    @tracker = Mixpanel::Tracker.new("XXXXXXX")

    @tracker.track(status.id, 'Tweets Received', { 'Hashtag' => tag, 'Message' => msg })

    puts 'Your code ran'
    end
  end
end

然后要在单独的进程中启动,您可以从命令行 运行 使用 bundle exec rake myappname:tweetstream