如何实现与http请求一起独立运行的计时器? [英] How to implement timer that runs independently along with http request?

查看:185
本文介绍了如何实现与http请求一起独立运行的计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ruby代码,可通过https触发php脚本.

I have a ruby code that triggers php script over https.

用例: php脚本通常在5分钟内完成,因此我为10分钟后的https请求设置了超时时间. 我需要一个计时器,可以说是在https请求开始7分钟后触发代码.

Use case: The php script usually finishes in 5 minutes so I have set up time out for https request after 10 minutes. I need a timer that would trigger code after let's say 7 minutes after the https request started.

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

I was thinking of using thread that I created just before I initiate https request. I am not sure if this the correct way to approach this. Maybe there is not need to use threads at all. I am using ruby 1.8.7 (2010-08-16 patchlevel 302) [i386-mingw32]. Also I don't now if I can 'kill' the thread on successful finish of https request.

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"

推荐答案

基本结构可能是这样的:

The basic structure could be like this:

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,代码将更快地完成.

...but of course you could change that sleep 1 to whatever polling interval you like. Polling is nicer than just forcing your original thread to sleep, because the code will finish faster if run_http_php_test is done before you hit your custom timeout value.

上面的大多数或所有代码都可以在run_http_php_test方法中,也可以直接插入...随便哪个.

Most or all of your code above can be in the run_http_php_test method, or inserted directly...whichever you'd prefer.

这篇关于如何实现与http请求一起独立运行的计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆