Run mult jobs in the background

liderbug

New member
Has anyone written the following? I want a web page where I call a function 8 to 12 times. The function takes 1.5 seconds to run. So call the function to the background so all calls run at the same time. Setting in a wait loop until all the jobs are done. Then gather the outputs and display the data.

Thanks
 
PHP don't supports background tasks natively. It is possible, but it's possible.
You can create a queue in the database where you can store all tasks that should be done in separate task. Then create a background-worker.php that will get one task marked as new from queue, mark it as in progress (to not take by another background worker) then it should do what is needed and mark the task as done (or failed) and take another task if exists or wait for new tasks
 
So, what I did was in the PHP: mysql "insert into jobs2bedone values ([numbers]) then at the end of the script (webpage)
shell_exec(sprintf('bash /usr/local/bin/fakeitout.bash > /dev/null 2>&1 &'));
The above "shell_exec" runs is a fraction of a second - ie 0.001 The fakeitout script is basically
while table jobs2bedone is not empty do XYZ
 
You can utilize the exec() function to run multiple processes in the background.
Here is a simple example showing how to call a function 8 to 12 times concurrently, wait for all jobs to finish, and then gather the outputs.
Code:
<?php

function longRunningTask($id) {
    sleep(1.5); // Simulating a long-running task
    return "Task $id completed.";
}

$processes = [];
$numberOfCalls = 10; // Adjust as needed (between 8 to 12)

for ($i = 1; $i <= $numberOfCalls; $i++) {
    $processes[] = popen("php -r 'echo longRunningTask($i);'", 'r');
}

$results = [];
foreach ($processes as $process) {
    $results[] = fread($process, 1024);
    pclose($process);
}

echo implode("\n", $results);
?>
The longRunningTask function simulates a task that takes 1.5 seconds to complete. The popen() function is used to execute the function in the background, allowing multiple calls to run simultaneously. After all processes are completed, the results are gathered and displayed.
Hope this helps.
 
Back
Top