I'm trying to extract a time consuming task to a separate process. Unfortunately, multi-threading does not really seem to be an option with PHP, but you can create new php processes, using popen.
The use case is this: there is a cronjob that runs every minute, which checks if there are any email campaigns that need to be sent. There could be multiple campaigns that need to be sent at the exact same time, but as of now it just picks up one campaign every minute. I would like to extract sending of the campaigns to a separate process, so that I can send multiple campaigns at the same time.
The code looks something like this (note that this is just a proof of concept):
crontab
* * * * * root /usr/local/bin/php /var/www/maintask.php 2>&1
maintask.php
for ($i = 0; $i < 4; $i++) {
$processName = "Process_{$i}";
echo "Spawn process {$processName}" . PHP_EOL;
$process = popen("php subtask.php?process_name={$processName} 2>&1", "r");
stream_set_blocking($process, false);
}
subtask.php
$process = $_GET['process_name'];
echo "Started sleeping process {$process}" . PHP_EOL;
sleep(rand(10, 40));
echo "Stopped sleeping process {$process}" . PHP_EOL;
Now, the problem I'm having is that popen will only spawn 2 processes at any time, while I'm trying to spawn 4. I can not figure out why. There doesn't appear to be any limit documented. Perhaps this is limited by the amount of cores I have available?