LoginSignup
6
7

More than 5 years have passed since last update.

godでtwitter gemのstreamingを常時監視するのに苦労した時のメモ

Last updated at Posted at 2016-01-25

Twitter監視するスクリプト作ったぞー

そんな時に神に降臨してほしい。
godのスタートアップをやってみた - mosson | Qiita

うまく動いてくれない

なんだかgodの設定例に従うとうまく動いてくれるのに、いざ自分のrubyスクリプトを神様に監視していただこうと思ってもうまくいかない。

streamtest.rb
require 'twitter'
#...
# 認証とか済ませてから
#...
stream = account.stream_api  # Twitter::Streaming::Clientオブジェクト
stream.user do |object|
  if obj == Twitter::Tweet
    p "ツイートを取得しました"
  end
end
streamtest.god
FILE_PATH = "#{Dir.pwd}/streamtest.rb" # あなたの常駐化させたいアプリ
God.watch do |w|
  w.name = "streamtest"
  w.start = "ruby #{Dir.pwd}.rb"
  w.keepalive
end

これで god -c ./streamtest.god -D しても

Shell
I [2016-01-25 04:11:58]  INFO: streamtest [trigger] process is not running (ProcessRunning)
I [2016-01-25 04:11:58]  INFO: streamtest move 'up' to 'start'
I [2016-01-25 04:11:58]  INFO: streamtest start: ruby /home/me/streamtest.rb
I [2016-01-25 04:11:58]  INFO: streamtest moved 'up' to 'up'
I [2016-01-25 04:12:03]  INFO: streamtest [trigger] process is not running (ProcessRunning)
I [2016-01-25 04:12:03]  INFO: streamtest move 'up' to 'start'
I [2016-01-25 04:12:03]  INFO: streamtest start: ruby /home/me/streamtest.rb
I [2016-01-25 04:12:03]  INFO: streamtest moved 'up' to 'up'
I [2016-01-25 04:12:08]  INFO: streamtest [trigger] process is not running (ProcessRunning)
I [2016-01-25 04:12:08]  INFO: streamtest move 'up' to 'start'
I [2016-01-25 04:12:08]  INFO: streamtest start: ruby /home/me/streamtest.rb
...

って感じで永遠に起動してくれない。
30分くらい触った結果、loop do ... end 以外のループ文(というかブロック文)とgodの相性が悪いのではないかと思った。
File.open do ... end とか Twitter::Streaming::Client.user do ... end があるとgodでは起動してくれない(のかすぐ終了してしまうかどちらか)っぽい。

改善策

  • それ自体がループしてなさそうで
  • streamtest.rbが死んだ時に終了してくれる
    そんなプログラムを間に挟めばいいのではないだろうか

=> foremanがあるじゃないかー
foreman で アプリケーションを動かす。- 7kaji | Qiita

というわけで、

まずProcfilestreamtest.rbと同じフォルダに。

Procfile
web: ruby ./streamtest.rb 

なににするか迷ったけどとりあえずwebに。

そしてstreamtest.godも書き換え。

streamtest.god(新)
God.watch do |w|
  w.name = "streamtest"
  w.start = "foreman start -d #{Dir.pwd}"
  w.keepalive
end

-dオプションでProcfileのロケーションを渡します。
#{Dir.pwd} としてるところはちゃんと絶対パスを指定したほうがいいです。本当は。これはまだ作りかけでファイルの位置がコロコロ変わるのでパスを取得するようにしています。

結果

動いた! ばんざい!
5秒毎に [trigger] process is not running (ProcessRunning) と出ることがなくなりました。
 
 

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7