2013-04-09 53 views
3

我正在使用LWP從網頁下載內容,並且我想限制它等待頁面的時間量。如何在perl中強制執行確定的超時?

my $ua = LWP::UserAgent->new; 
$ua->timeout(10); 
$ua->env_proxy; 
$response = $ua->get("http://XML File"); 
$content = $response->decoded_content; 

問題是服務器偶爾會發生死鎖(我們試圖找出原因),並且請求永遠不會成功。由於服務器認爲它是活動的,因此它保持套接字連接打開,因此LWP :: UserAgent的超時值對我們來說沒有好處。對請求執行絕對超時的最佳方式是什麼?

只要超時達到極限,它就會死亡,我無法繼續使用腳本! 整個腳本處於循環狀態,它必須按順序獲取XML文件。 我真的很想正確處理這個超時,並讓腳本繼續到下一個地址。有誰知道如何做到這一點?謝謝!!

+0

[上LWP :: UserAgent的請求的方法真超時(可能的重複http://stackoverflow.com/questions/73308/true-timeout -on-lwpuseragent-request-method) – sixtyfootersdude 2016-02-24 22:56:36

回答

7

我在https://stackoverflow.com/a/10318268/1331451之前遇到類似的問題。

你需要做的是添加一個$SIG{ALRM}處理程序並使用alarm來調用它。您在撥打電話前先設定alarm,然後直接取消。然後你可以看看你返回的HTTP :: Result。

該警報將觸發信號,Perl將調用信號處理程序。其中,您可以直接填寫填寫內容,也可以填寫diedieeval用於die否打破整個程序。如果調用信號處理程序,則alarm會自動重置。

您也可以在處理程序中添加不同的die消息,稍後再與[email protected]區分,就像@larsen在他的回答中所說的。

下面是一個例子:

my $ua = LWP::UserAgent->new; 
my $req = HTTP::Request->new; 
my $res; 
eval { 
    # custom timeout (strace shows EAGAIN) 
    # see https://stackoverflow.com/a/10318268/1331451 
    local $SIG{ALRM} = sub { 
    # This is where it dies 
    die "Timeout occured..."; 
    }; # NB: \n required 
    alarm 10; 
    $res = $ua->request($req); 
    alarm 0; 
}; 
if ($res && $res->is_success) { 
    # the result was a success 
} 
+0

非常感謝你的幫助......讓我測試一下。 – 2013-04-09 11:16:39

+0

這看起來很棒,但對我來說效果並不如預期。發佈一個新問題來討論它:http://stackoverflow.com/q/35614328/251589 – sixtyfootersdude 2016-02-24 22:46:09

+0

供參考:我複製/粘貼你的答案重複問題在這裏:http://stackoverflow.com/a/35614804/251589和這裏:http://stackoverflow.com/a/35614858/251589如果你想在那裏發佈答案,留下我的評論,我會刪除我的答案。你值得代表。 – sixtyfootersdude 2016-02-24 23:00:33

0

通常,如果要捕獲和控制可能死亡的代碼段,可以使用eval塊。

while(…) { # this is your main loop 
    eval { 
     # here the code that can die 
    }; 
    if ([email protected]) { 
     # if something goes wrong, the special variable [email protected] 
     # contains the error message (as a string or as a blessed reference, 
     # it depends on how the invoked code threats the exception. 
    } 
} 

您可以找到的文檔中進一步信息爲the eval function