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();