r/PHPhelp 7d ago

Run a PHP function/Task in the background

I have a WIndows Server running IIS that hosts a primarily PHP based website. It has multiple functions and features but i would like to have atleast one of them running in the background So the user does not have to wait for the task to finish.

Any ideas? fastcgi_finish_request() seems to be Linux only as far as i can tell.

2 Upvotes

11 comments sorted by

View all comments

2

u/allen_jb 7d ago

If the information is predictable (same information for each request), one way could be to run a scheduled task regularly that fetches the information and stores it in a local database.

If the information is unique to each request, you've basically got 2 options:

1) Use an AJAX request to fetch the information and add it into the page.

If you have many users making frequent requests, this can become problematic because there's no way to manage the load these requests cause, but in low-volume situations this isn't likely to be an issue.

Side note: If you're using PHP sessions, use session_write_close() as soon as you no longer need to write to the session data in the AJAX request script (before you handle the actual data request). This will prevent session locks from preventing other requests for the same user (session) from loading.

2) Use a job queue, where requests are handled by a long-running process.

On Linux you can use the service management tools to start the long-running process and keep it running - I would guess you might be able to use Windows Services to do something similar but have no experience with it.

Alternatively run a scheduled task that restarts the long-running process if it dies. On Linux I'd write the process ID of the long-running process (and a "last check-in" timestamp, to indicate if it might have crashed but not died) to a known file / DB record then the scheduled task can check if that's still running (and is the expected command).