Search code examples
phplaravellaravel-4cronrace-condition

Laravel 4.2 prevent query from running at the same time


Using laravel 4.2, I have a Cron job which runs every minute, it takes the jobs list from the database in a similar way to this:

$records = DB::table('jobs')->where('finished', '=', 0)->
whereBetween('created_at', [Carbon::now(),Carbon::now()->addMinutes(2)])->get();
// Process records
..

After finishing, it will update "finished" field to 1 .

Now since the cron job is running every minute, i need to make sure that if the cron job started before the previous one finishes, it would not run or not select the same records.


Solution

  • Solved this issue using transaction & lockForUpdate:

    DB::beginTransaction();
    $records = DB::table('jobs')->where('finished', '=', 0)->lockForUpdate()->get();
    // process
    DB::commit();