Skip to content
Home » Web » PHP » PHP Background Job Example

PHP Background Job Example

Web administrators might have some routine jobs to be executed in the background periodically by triggering PHP web pages. Most of the times, the web pages were waiting for the server response and seemed hanged. Even worse, no other normal users can get responses.

The solution is to disconnect from the foreground of web administrators once the routine job begins, this can make the job switch to background and the web administrator can get the response with no waits. But this is an irreversible process, once it goes to background, there is no way to get it foreground. It only can be stopped by restarting httpd service.

This is how I did it in 5 steps:

<?php
echo "Disconnected"; // Notify the user.
header("Connection: Close"); // Set connection state of header.
header("Content-Length: " . ob_get_length()); // Set content-length of header.
ob_end_flush(); // Flush output buffer and turn it off.
flush(); // Flush all output to user and disconnect without waiting.

// Do some background jobs. For example, to print the monthly payroll report.
printPayrollReport();
?>

If you want to interrupt or stop the jobs, please restart httpd service like this:

[root@test ~]# service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd:                                            [  OK  ]

Since you have been disconnected by the server, you may close, then open the web browser to start a new session for other tasks.

Leave a Reply

Your email address will not be published. Required fields are marked *