Appearance
Run PHP Task Asynchronously
To run a PHP task asynchronously, you can use the pcntl_fork() function to create a new process that runs the task in parallel with the main script. This allows the main script to continue executing without waiting for the task to complete.
Note: The pcntl extension is required, and this approach only works in CLI environments on Linux/Unix systems. It is not supported on Windows or in web server environments (FPM/CGI).
Example of running a PHP task asynchronously with the pcntl_fork() function
php
<?php
// Start the task as a new process
$pid = pcntl_fork();
if ($pid == -1) {
// Error: Unable to fork
exit();
} elseif ($pid) {
// Parent process
// Wait for the child process to prevent zombie processes
pcntl_wait($status);
// Do other tasks here while the task runs in the background
} else {
// Child process
// Run the task here
exit(); // Must exit to prevent child from continuing as parent
}
?>
<div class="alert alert-info flex not-prose">Watch a video course Learn object oriented PHP
</div>
Note: This is not recommended for long-running tasks or modern web applications. For those, prefer message queues or async libraries like php-resque (a PHP port of the Ruby Resque library).