如何在发生故障时重试操作

时间:2013-07-31 00:59:17

标签: php

我正在使用PHP脚本按其ID播放YouTube视频,并获取视频标题和相关视频。

我的问题是,有时页面会在标题或相关视频链接出现之前完成加载。

我正在使用000WebHost.com免费虚拟主机;它有一些限制,例如出于安全原因禁用某些功能,包括set_time_limit(),所以我不能使用它。

例如,如果长度为零,我是否可以重试加载标题和视频链接?

这样的事情:

<?php
    if (strlen($title) == 0) {
        // Do something here to retry loading the title from
        // http://www.youtube.com/get_video_info?video_id=VIDEO_ID        
    }
?>

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

为什么不使用do-while循环?这将继续尝试加载视频信息,直到它超时或收到有效的响应:

/**
 * @return boolean Whether the given argument is a valid
 * YouTube API response
 **/
function isValidApiResponse($response)
{
    // ... your logic here ... //
}

$videoId     = 'someId';
$timeoutTime = time() + 10; // Stop trying after 10 seconds

do {
    $apiResponse = CURL::get("https://gdata.youtube.com/feeds/api/videos/{$videoId}?v=2");
    $pageLoaded  = isValidApiResponse($apiResponse);
} while ((time() < $timeoutTime) AND (! $pageLoaded));

if ($pageLoaded) {
    // SUCCESS: Page loaded properly
} else {
    // ERROR: Timed out
}