Ruby脚本每30秒ping一次URL

时间:2016-12-12 17:27:12

标签: ruby

有没有办法使用Ruby脚本每隔30秒ping一次URL?

require 'net/http'

http = Net::HTTP.new('www.google.com',80)
response = http.request_get('/')
p response.status

2 个答案:

答案 0 :(得分:5)

根据您的使用情况,可能会有一个loop sleep的简单工作:

require 'net/http'

loop do
  http = Net::HTTP.new('www.google.com')
  response = http.request_get('/')
  p response.code

  sleep 30      
end

答案 1 :(得分:3)

只要ping持续时间小于30秒,此代码就会每30秒ping一次。

require 'net/http'

time_step = 30 #s

loop do
  start = Time.now
    http = Net::HTTP.new('www.google.com',80)
    response = http.request_get('/')
    p response.code # -> "302"
  duration = Time.now-start

  sleep (time_step - duration) unless duration > time_step
end