nyan-cat
nyan-cat

Reputation: 630

PHP service (daemon)

I have a website that provides some sort of service via REST API. All functionality has regular HTTP request-response logic. But additionally I need another PHP script that does some continuous stuff. On the one hand, this script should have an access to all core service functionality (core engine, stored procedures, etc). On the other hand, this script should keep persistent connection to third-party service and read some information from it from time to time. Additionally this script should be fault-tolerant, and it should be guaranteed that only one instance of this script is running at any time. Also there are some reasons why I can't put this task on the Cron service instead of infinite script running.

The best idea that I have at this moment is to write regular PHP script that starts with set_time_limit(0) and contains infinite loop with my stuff action and sleep after it. This script will be launched manually. Additionally I can protect this script with some sort of password to make sure that no one else could run it. What do you guys think about this solution? Won't such solution affect some unwanted FastCGI side-effect? How can I make this solution fault-tolerant? And how can I stop this script, or check if it is running? And the last thing: how can I run this script via HTTP request so that it won't block anything (kinda background-running CURL or something). Thanks!

Upvotes: 1

Views: 634

Answers (1)

Shi
Shi

Reputation: 4258

First of all, why is it not possible to use crond for it?

I suggest you start the script via crond once per for example 15 minutes. This way, the script will be unavailable for at most 15 minutes in case it crashes. To make sure the script runs only once, you implement what all other daemons do - a PID file - use posix_getpid() for that. If a process with that PID exists, terminate the script. If not, a previous instance crashed and the script should run again.

Or even better, write an Upstart script for that (if you are on Debian/Ubuntu). It will then be started automatically at system start, and you can bring it down or start it again easily anytime via service script start and service script stop. You can check the status by issuing service script status.

You put the script on the server outside any htdocs directory. This way it is not exposed to the web and cannot be started by via a HTTP request. You additionally can check the SAPI to be cli by using php_sapi_name().

And why do you want to run that script via HTTP? It is a daemon, so it starts at system startup.

You should also look at a similar question: Run php script as daemon process.

Upvotes: 2

Related Questions