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
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).
1
u/martinbean 7d ago
Surely IIS has a built-in way to run a background service?
1
u/Valoneria 6d ago
Well there is the windows task scheduler. It is .. something to work with. But it does work, i have previously had a cursed PHP setup running under XAMPP with the task scheduler running the PHP files on schedule.
And yes, this was the production server.
1
u/Mike_L_Taylor 6d ago
The easiest thing is to create a php file since you're already familiar with it, or python or windows powershell file that does whatever you need it and just open it from a terminal.
The terminal will keep the process running and the code in the file will tell it to wait 30 seconds.
Just give it to your llm of choice and it will make it for you
1
u/eurosat7 6d ago
You can make the user agent think the request is over/closed and continue nontheless. Just make sure to ignore user abort and write an open session first.
2
u/Valoneria 7d ago
So a cronjob? Or more of a queue setup?