LoginSignup
0
0

More than 1 year has passed since last update.

laravel background で定期処理

Posted at

cron でバックグラウンドで処理したい場合がある

今回は、photoが人物画像かどうをチェックする

・まず、一度だけ処理する場合

DB
person_at フィールド を 初期値 NULL で作成

hoge.php
$data = Photo::query()
    ->where('person_at',NULL)
    ->take(25)
    ->get();

$now =  Carbon::now();

//ここで処理をしていく
$res = [];
foreach ($data as $v) {

    $res[] = [
        'id' => $v->id,
        'person' => 1,
        'person_at' => $now,
    ];

}


$model = new Photo;
//updated_atの更新はしない
$model->timestamps = false;
$model->upsert($res,['id']);


最終処理の履歴があれば処理しないので、cronに仕掛けても1度しか処理されない。

・定期的にチェックしたい

DB
person_at フィールド を 初期値 current_timestamp() で作成

hoge.php
$data = Photo::query()
    ->orderBy('person_at', 'ASC')
    ->take(25)
    ->get();

$now =  Carbon::now();

$res = [];
foreach ($data as $v) {

    $res[] = [
        'id' => $v->id,
        'person' => 1,
        'person_at' => $now,
    ];

}

$model = new Photo;
//updated_atの更新はしない
$model->timestamps = false;
$model->upsert($res,['id']);

最終処理が古いものから順に再度処理していくので、cronに仕掛けることで定期的に何度も処理される。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0