我已经构建了一个小型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
答案 0 :(得分:0)
您可以将此作为佣金任务。将命名空间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