LoginSignup
1
1

More than 5 years have passed since last update.

pthreadsを使わずにcronだけでPHPのバッチスクリプトを平行処理するアイデア

Last updated at Posted at 2018-09-20

はじめに

pthreadsを使わない強い理由があるわけではないのですが、すでにあるPHPのバッチスクリプトであっても、ちょっとした工夫で平行処理できるアイデアがあるので紹介します。
pthreadsについては、下記の記事に詳しく書いてあるので参照ください。

尚、並列(pararell)処理というと、怒られそうなので、並行(concurrent)処理という言葉を使っています。

結論

何かしらユニークなIDをパーティショニングして、バッチスクリプトの実行時引数として渡してあげることで処理を分散、平行処理することができます。

サンプル

itemsテーブルのidを3分割して取得し、それに対して何らか処理をするサンプルです。

// /path/to/batch/script.php
// 前処理など、いろいろ省略

list($partitionIndex, $partitionSize) = explode('/', $argv[1] ?? '0/1');

$items = $itemRepository->fetchByPartition($partitionIndex, $partitionSize);

foreach ($items as $item) {
    // do something...
}
class ItemRepository
{
    public function fetchByPartition($partitionIndex = 0, $partitionSize = 1)
    {
        $sql = <<<SQL
SELECT * FROM items
WHERE id % {$partitionSize} = {$partitionIndex}
ORDER BY id ASC
LIMIT 1000
;
SQL;

        $statement = $this->connection->query($sql);
        return $statement->fetchAll();
    }
}
$ crontab -e

*/5 * * * * php /path/to/batch/script.php 0/3
*/5 * * * * php /path/to/batch/script.php 1/3
*/5 * * * * php /path/to/batch/script.php 2/3

おわりに

泥臭い方法ではありますが、十分に処理時間を短縮できる方法かと思います。
PHPに限ったアイデアではないので、Pythonなど他の言語でも活用していただけると幸いです。

ではでは。

1
1
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
1
1