LoginSignup
6
3

More than 5 years have passed since last update.

PHPで重い処理を非同期で実行

Last updated at Posted at 2019-02-08

PHPで重たい処理を非同期実行して、ストリーミングで処理途中かどうかを返す方法

コード


function post()
{
    echo "処理を開始します。<br>\nしばらくお待ちください<br>\n<br>\n";
    ob_end_flush();
    ob_start('mb_output_handler');

    $ps_cmd = 'ps x | grep ${重たい処理書いたファイル} | grep -v grep';
    exec($ps_cmd, $output);

    if (count($output) <= 0) {
        $cmd = '${重たい処理書いたファイル} > /dev/null &';
        exec($cmd);
    }

    while (true) {
        sleep(1);
        $output = null;
        exec($ps_cmd, $output);

        echo ".";

        ob_flush();
        flush();

        if (count($output) <= 0) {
            break;
        }
    }

    echo "<br>\n<br>\n処理が完了しました<br>\n";
    ob_flush();
    flush();
    ob_end_clean();
}

説明的な

ブラウザからURL何度叩いても、プロセス立ちまくらないように

$ps_cmd = 'ps x | grep ${重たい処理書いたファイル} | grep -v grep';
exec($ps_cmd, $output);

if (count($output) <= 0) {
// ~ 省略 ~

関数


# バッファ出力
ob_end_flush();

# バッファリング開始
ob_start('mb_output_handler');

# バッファ出力
ob_flush();
flush();

# 終了
ob_end_clean();

実行的な

6
3
1

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
6
3