LoginSignup
0

More than 5 years have passed since last update.

pythonのmultiprocessingを使って、PHPのスクリプトを平行処理する

Posted at

はじめに

pthreadsを使わずにcronだけでPHPのバッチスクリプトを平行処理するアイデア」で紹介した方法だと、平行数の分だけcronの設定を追記しなければいけないので、Pythonmultiprocessingを使ってスッキリさせます。

$ 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

実装サンプル

#!/usr/bin/python
# -*- coding: utf-8 -*-
# /path/to/batch/script.py
import os
import sys
from multiprocessing.pool import Pool

if __name__ == "__main__":

    args = sys.argv
    id_partition_size = 1

    if len(args) == 2:
        id_partition_size = int(args[1])

    def _batch(arg):
        os.system('php /path/to/batch/script.php {}/{}'.format(arg['partition_index'], arg['partition_size']))

    def run(id_partition_size):
        args = []
        for index in range(0, id_partition_size):
            args.append({'partition_index': index, 'partition_size': id_partition_size})

        pool = Pool(processes = id_partition_size)
        pool.map(_batch, args)

    run(id_partition_size)

これで、cronには下記の1行を設定するだけになりました。
並列数を変更する場合は、実行時引数を変更します。

$ crontab -e

*/5 * * * * python /path/to/batch/script.py 3

おわりに

python 2.7でも3.5でも動作したので、ほとんどのサーバーで追加インストールなしで動くはずです。
既存のソースコードを活用しつつも、手軽に分散・平行処理できるかと思いますので、活用いただければ幸いです。

ではでは。

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