LoginSignup
9
10

More than 5 years have passed since last update.

RubyでCron処理みたいな事をしたい

Posted at

公開しているサーバーの負荷状況を仕事してる時にも知りたいと
思ってNotificationの出し方なんかを調べてたら何かが降りてきて数分毎にNotificationだそうとか考えた。

使ったGemとか

  • Nokogiri
    • スクレイピングの大御所
  • Menchanize
    • Nokogiriを使いやすくしてくれる
  • Clockwork
    • Cronの代替。時間が来ると実行してくれる。

コード

require 'clockwork'
require 'mechanize'

module Clockwork
  handler do |job|
    job.call
  end
  every(
    1.minutes,
    lambda do
      url = 'http://path/to/site'

      items = []
      agent = Mechanize.new
      page = agent.get(url)
      node = page.search('node')
      node.search('item').each do |item|
        value = []
        item.search('hoge').each do |hoge|
            # 何かしらのデータの取得
        end
        items.push(value)
      end
      message = ""
      items.each do |item|
        # 何かしら通知文作成
      end
      `osascript -e 'display notification "#{message}" with title "#{page.title}"'`
    end
  )
end

Clockworkのモジュールの中でJobをコールして1分おきにlambda doの中身を実行する。
lambda doの中ではMenchanizeでスクレイピングをして結果をosascript -e ....でNotificatioに流す仕組み

後はAutomatorとかで起動時に実行すればいいんじゃないかなぁって。

参考にしたサイトとか

http://qiita.com/manuluu/items/cfba3e7734036e389768
http://www.xmisao.com/2013/10/05/ruby-www-mechanize.html
http://www.ownway.info/Ruby/index.php?clockwork%2Fabout
http://xoyip.hatenablog.com/entry/2014/02/17/222721

9
10
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
9
10