0

我有一个通过 https 触发 php 脚本的 ruby​​ 代码。

用例: php 脚本通常在 5 分钟内完成,所以我在 10 分钟后为 https 请求设置了超时。我需要一个计时器,它会在 https 请求开始后 7 分钟后触发代码。

我正在考虑使用我在发起 https 请求之前创建的线程。我不确定这是否是解决此问题的正确方法。也许根本不需要使用线程。我正在使用 ruby​​ 1.8.7 (2010-08-16 patchlevel 302) [i386-mingw32]。如果我可以在成功完成 https 请求时“杀死”线程,我现在也不会。

uri = URI.parse(url)
start = Time.new
http_read_timeout=60*10

connection = Net::HTTP.new(uri.host, 443)
connection.use_ssl = true
begin   
        response = connection.start() do |http|
            http.open_timeout =  50
            http.read_timeout = http_read_timeout
            http.request_get(uri.request_uri)
            # here I need to place a code that is triggered 
            # in case of custom timeout is reached
        end
rescue Timeout::Error
#  "Connection failed
    time_out_message ="security time out - after #{http_read_timeout} sec"
return time_out_message         

end

puts "finished"
4

2 回答 2

1

ruby 1.9.3 实现了具有超时功能的超时模块。你可以在这里看到。如果向下滚动,您可以单击显示源并查看超时方法的定义。如果您不想升级到 ruby​​ 1.9.3,可以复制它(我建议升级,因为 1.8.7 与 1.9.3 相比非常慢)

于 2012-05-24T05:44:43.737 回答
1

基本结构可能是这样的:

seconds_timer = MyDelay
counter = 0

test_thread = Thread.new do
  run_http_php_test
end

while test_thread.alive?
 counter += 1
 if counter > seconds_timer
   handle_custom_timeout_somehow       
   # if you want to halt run_http_php_test: 
   test_thread.kill if test_thread.alive?
   # otherwise:
   break
 end
 sleep 1
end
# the below doesn't apply if you kill the run_http_php_test thread
test_thread.join if test_thread.alive?

...但当然,您可以将其更改sleep 1为您喜欢的任何轮询间隔。轮询比仅仅强制您的原始线程休眠更好,因为如果run_http_php_test在您达到自定义超时值之前完成,代码将更快地完成。

上面的大部分或全部代码都可以在 run_http_php_test 方法中,或者直接插入......无论你喜欢哪个。

于 2012-05-24T15:15:38.413 回答