Run PHP script in background on Apache start/restart(Windows Server)
I come up with a solution :)
APACHE_HOME = C:/PATH/TO_APACHE
%APACHE_HOME%\bin\httpd.exe
to %APACHE_HOME%\bin\httpdVendor.exe
php myscript.php%APACHE_HOME%\bin\httpdVendor.exe -k runserviceexit 0
%APACHE_HOME%\bin\httpd.exe
Tested on : Windows 7, Apache 2.4, Advanced Bat to Exe Converter 2.92
Use built in Windows Task Scheduler which triggers .bat
script, which calls curl with defined url.
- Download curl from http://curl.haxx.se/download.html and extract curl.exe on any directory, but we will use
c:\backgroundtasks
Adjust script below to your needs:
cd c:\
cd c:\backgroundtasks
curl http://localhost/path/to/script.php
exit
Configure Task Scheduler to run as basic task:
- General tab - as system account (to run when you are not logged in server)
- Triggers tab - adjust frequency
- Settings tab - at bottom set
If the task is already running...
toStop the existing instance
The best method here would be to use Windows services dependencies.
Make a php-websocket-server.cmd
file with any necessary environment settings (e.g. changing to a directory, setting PATH, etc...) with the last line:
php myscript.php
Install the Windows Server Resource Kit Tools, to get srvany
and instsrv
to create a user defined service. Note the install path as you'll need it in the next step.
Open a cmd
shell and run:
<path_to_resource_kit>\instsrv PHPWebSocketServer <path_to_resource_kit>\srvany.exe
Next, create a file php-websocket-server.reg
containing the following (update for your environment):
Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PHPWebSocketServer\Parameters]"Application"="c:\\path\\to\\php-websocket-server.cmd"
Import it by double-clicking or regedit /s php-websocket-server.reg
Back in your cmd
shell:
sc config Apache2.4 depend= PHPWebSocketServer
to make the Apache2.4* service depend on your php service. Now, when Apache is started, the php service will be brought up first. And likewise, if you stop the php service Apache will stop along with it.
*the howto indicates that the service is named "Apache2.4" but you may want to verify in your installation.