在ruby代码中添加连接超时

时间:2017-05-03 10:21:23

标签: ruby

如何在此ruby代码中配置连接超时?

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(url)
request.basic_auth("user", "pass")

例如每1秒钟我想尝试连接并打印结果。

1 个答案:

答案 0 :(得分:0)

您可以使用调度程序gem(例如Rufus Scheduler)来安排任务每秒运行一次。

安装宝石

gem install rufus-scheduler

示例代码:

require "net/http"
require 'uri'
require "openssl"
require "rufus-scheduler"

url = URI("https://google.com")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

scheduler = Rufus::Scheduler.singleton

scheduler.every '1s' do 
    p Net::HTTP::get(url)
end

scheduler.join