简体   繁体   中英

Running Cron jobs in parallel (PHP)

In the past, I ran a bunch of scripts each as a separate cron job. Now I'd like to run a controller script with one cron job, then have that call the scripts separately (and in parallel, all at the same time), so I don't have to create a new cron job every time I add another script.

I looked up pcntl_fork() but we don't have that installed. Can fsockopen() do this as well?

A few questions:

  1. I saw this example, http://phplens.com/phpeverywhere/?q=node/view/254 , that uses fsockopen() . Will this allow me to run PHP scripts in parallel? Note, the scripts don't interact, but I would still like to know if any of them exited prematurely with an error.

  2. Secondly the scripts I'm running aren't externally accessible, they are internal only. The script was previously run like so: php -f /path/to/my/script1.php . It's not a web-accessible path. Would the example in #1 work with this, or only web-accessible paths?.

Thanks for any advice you can offer.

You can use proc_open to run multiple processes without waiting for each process to finish. You will have a process handle, you can terminate each process at any time and you can read the standard output of each process.

You can also communicate via pipes, which is optional.

Passing 1st param php /your/path/to/script.php param1 "param2 x" means starting a separate PHP process.

proc_open (see Example #1)

Ultimately you will want to use an infinite while loop + usleep (or sleep) to avoid maxing out on the CPU. Break when all processes finish, or after you killed them.

Edit: you can know if a process has exited prematurely.

Edit2: a simpler way of doing the above is popen

Please correct me if I'm wrong, but if I understand things correctly, the solution Tiberiu-Ionut Stan proposed implies that starting the processes with proc_open and waiting for them to finish will not be run as a cron script, but is part of a running program/service, right?

As far as I understand the cron jobs, the controller script user920050 was thinking of using would be started by cron on a schedule and each new instance would launch the processes all over again, do the waiting for them to finish and probably run in parallel with other cron-launched instances of the controller script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM