在try块中使用break作为最后一个语句,仅在成功时保留无限循环:
while (true) {
try {
//do a thing
insertIntoDb($data);
break;
}
catch (Exception $e) {
writeError($e);
}
// sleep 200ms to give the MySQL server time to come back up
usleep(200000);
}
您也可以使用for循环来限制重试次数:
// do 3 retries before aborting finally
for ($i=1; $i <= 3; $i++) {
try {
//do a thing
insertIntoDb($data);
break;
}
catch (Exception $e) {
writeError($e);
}
// sleep 200ms to give the MySQL server time to come back up
usleep(200000);
}
注意usleep()调用:
这很重要,否则PHP进程会尽可能快地重试所有资源(100%CPU).您可以调整值以满足您的需求. (在你的情况下,可能200ms太长或太短)
另请注意,您可能需要在失败时重新连接到MySQL DB!在我的示例中,我没有包含该案例的代码.