1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | #!/usr/local/bin/ruby require 'net/http' require 'net/smtp' # # Given a web-site and link, return the stock price # def getStockQuote(host, link) # Create a new HTTP connection httpCon = Net::HTTP.new( host, 80 ) # Perform a HEAD request resp = httpCon.get( link, nil ) stroffset = resp.body =~ /class="price">/ subset = resp.body.slice(stroffset+14, 10) limit = subset.index('<') return subset[0..limit-1].to_f end # # Send a message (msg) to a user. # Note: assumes the SMTP server is on the same host. # def sendStockAlert( user, msg ) lmsg = [ "Subject: Stock Alert\n", "\n", msg ] Net::SMTP.start('localhost') do |smtp| smtp.sendmail( lmsg, "rubystockmonitor@localhost.localdomain", [user] ) end end # # Our main program, checks the stock within the price band every two # minutes, emails and exits if the stock price strays from the band. # # Usage: ./monitor_sp.rb <symbol> <high> <low> <email_address> # begin host = "www.smartmoney.com" link = "/eqsnaps/index.cfm?story=snapshot&symbol="+ARGV[0] user = ARGV[3] high = ARGV[1].to_f low = ARGV[2].to_f while 1 price = getStockQuote(host, link) print "current price ", price, "\n" if (price > high) || (price < low) then if (price > high) then msg = "Stock "+ARGV[0]+" has exceeded the price of "+high.to_s+ "\n"+host+link+"\n" end if (price < low) then msg = "Stock "+ARGV[0]+" has fallen below the price of "+low.to_s+ "\n"+host+link+"\n" end sendStockAlert( user, msg ) exit end sleep 120 end end |
1 2 3 4 5 | [mtj@camus]$ ./monitor_sp.rb ibm 83.00 75.00 mtj@mtjones.com current price 82.06 current price 82.32 current price 82.75 current price 83.36 |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |