使用数据库事务重试 Laravel PHP 脚本 10 秒

Retrying Laravel PHP script with database transaction for 10 seconds

我正在使用 Laravel 4.2 我有一个巨大的 try/catch 块用于 运行 数据库事务。有多种类型的异常。

$startTime = 0;
try {

DB::beginTransaction();
//code

DB::commit();

}catch(Exception1 $e){

DB::rollBack();
//so something with this, save in db and throw new Exception
if($startTime < 10) retry the whole process

}catch(Exception2 $e){

DB::rollBack();
//so something with this, save in db and throw new Exception
if($startTime < 10) retry the whole process

}catch(Exception $e){

DB::rollBack();
//so something with this, save in db and throw new Exception
if($startTime < 10) retry the whole process
}

我希望整个过程重试 10 秒。每次失败我都需要回滚更改并重试。

我怎样才能正确地做到这一点? 谢谢

我会将 "try" 中的整个代码包装到执行 transaction/rollback 和 运行 的函数中,只要它 returns false 并且它运行ning 不到 10 秒前开始。我脑子里打字,也许我漏掉了什么,但我希望你能明白:

function doIt() {
  try {
    DB::beginTransaction();

    /**
     * whatever
     */

    DB::commit();

    return true;
  } catch (Exception $e) {
    DB::rollBack();
    /**
     * do something more if you need
     */

    return false;
  }
}

$start = time();
do {
  $IdidIt = doIt();
} while(!$IdidIt && (time() - $start <= 10));

更新,根据评论:

function tryFor10Seconds(Closure $closure) {

  $runTheClosure = function ($closure) {
    try {
      DB::beginTransaction();

      $closure();

      DB::commit();

      return true;
    } catch (Exception $e) {
      DB::rollBack();

      // handle the exception if needed, log it or whatever

      return false;
    }
  };

  $start = time();
  do {
    $result = $runTheClosure($closure);
  } while(!$result && (time() - $start <= 10));

  return $result;
}

所以,基本上你会这样称呼它:

$success = tryFor10Seconds(function() use ($model1, $model2, $whatever) {
  $model1->save();
  $model2->save();
  $whatever->doSomethingWithDB();
});

if (!$success) {
  // :(
}