LoginSignup
0
0

More than 1 year has passed since last update.

cron で 全データに対し、1日1回処理をする

Last updated at Posted at 2022-12-05

cronを使って以下の処理を行いたいときがある

・ランダムな時間
・全データに関して1日1回は処理をしたい
・しかし、DBから100件取り出しても 15件しない時とかある

上記の処理をするアルゴリズムが複雑すぎたのでまとめて書いておく。

User.php

    public static function cronRand($syori,$day_fun)
    {
//        $syori = 100;//一度に処理するレコード数
//        $day_fun = 1440;//1日の分数(2日に一回なら2880とする)

//        ランダムにIDを取得
        $rand_ids = User::query()//単数形 User
        ->select('id')
            ->inRandomOrder()
            ->take($syori)
            ->pluck('id')->toArray();//リスト形式で取得

        $user = User::query()//単数形 User
            ->whereIn('id',$rand_ids)
            ->paginate($syori);//take でなく、ここに直接1ページに表示するカウントを指定


        $record = User::query()//単数形 User
            ->paginate($syori);//take でなく、ここに直接1ページに表示するカウントを指定



        $all_record = $record->total();

        $page = $record->lastPage();//レコード数(何ページあるかを調べるか)

        $tmp = $day_fun/$page;
        $wariai = ceil($tmp);//1日1回に足りない程度
        $jikkou_flag = mt_rand(1,$wariai);//jikkou_flag が 1のときに実行すれば良い


        //オブジェクトを配列に
        $tmp = json_decode(json_encode($user), true);
        $data = $tmp['data'];

        //テスト配列をカットしてみる
        $data = array_splice($data, 0,3);

        $dummy = $data[0];
        $dummy['id'] = 0;

        //7個たりないので配列を埋める
        $tarinai = $syori-count($data);
        $data += array_fill(count($data), $tarinai, $dummy);

//        foreach ($data as $v) {
//            echo $v['id']." : ".$v['name']." <br>";
//        }
//
//        echo "all_record : " . $all_record . "<br>";
//        echo "処理ペース : " . $wariai . " 回 に 1回<br>";
//        echo "実行フラグ : " . $jikkou_flag . " が1のとき実行<br>";
//        echo "総ページ数 " . $page . "";

        if($jikkou_flag == 1){
//            pd("処理実行");
            return $data;
        } else {
            return false;
        }



    }

ここでデータが帰ってきた場合のみ、処理を実行すればOK

HogesController.php

//        100件を一気に読み出し、1440分(1日) に 1回の割合で処理
        $res = User::cronRand(100,1440);
        print_r($res);

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