我有一个 PHP 脚本,它通过/向 API 接收和发送大量数据。它工作正常,但我的脚本调用的 API 有时会中断并返回500 Server Error。在这种情况下,我想让我的脚本重新启动
我怎样才能做到这一点?我试过了,header("Location: http://example.com/myscript.php");
但没有成功。
编辑(因为有 6 人点击了这个问题):
好的,所以我有我的myscript.php,它应该作为 crontab 运行..
这个myscript.php将大量数据发送到外部/远程 API(它不是我的 API,所以我无法在这里解决问题)。我发送的数据经过检查和验证)
myscript.php首先询问 API 哪些数据已经发送给它并跳过它,所以当myscript.php可以重新启动时,它会在某个时候完成:)
听起来您并不是说您的脚本失败,而是您的脚本使用了偶尔会失败的 Web API。
如果 API 由于您发送给它的数据而返回错误,您应该重新检查您的代码以找出如何防止创建此类数据。
另一方面,如果 API 在您向其发送数据时随机失败而在后续请求中成功,则最好停止使用该 API。
如果您因任何原因而坚持使用它,并且只想重试调用而不是中止脚本,我认为您可以在不重新启动整个脚本的情况下执行此操作。
$max_attempts = 4; // Decide on a reasonable number of times to retry the call
while ($max_attempts--) {
// Try the API call up to the specified maximum number of attempts
$returned_data = $api->call($sent_data);
// Stop trying when you get a successful response
if ($returned_data != '500 Server Error') break;
}
Run Code Online (Sandbox Code Playgroud)
如果随机故障相对较少,这种方法应该会显着降低整体故障率。如果您需要在后续尝试的 API 调用之前重复代码的某些部分,您也可以将它们包含在重试循环中。
如果达到最大重试次数但仍然没有好的数据,则可能发生了异常糟糕的事情,因此您应该停止尝试。
if ($returned_data == '500 Server Error') die ("The API probably isn't working at all");
Run Code Online (Sandbox Code Playgroud)
从理论上讲,如果有办法在每次 API 调用失败时重新启动整个脚本,那么如果 API 确实停止工作,那么您的脚本似乎会在无限循环中重新启动。