cron-like execution of PHP code more often than every minute
A friend of mine recently asked me how to modify a PHP script that collects data into an RRDtool database so it could be triggered more often than once per minute. He is currently using cron(8) to trigger the script.
Of course cron(8) has a granularity of 1 minute so there is nothing that can be done there.
The basic solution is to start the script once and have it loop infinitely with each loop iteration performing the action and then waiting until the next time the action should be performed. Thus the run interval can be specified with sub-second precision.
There are a few minor catches though:
-
In order to not use CPU when waiting for the next execution time, the script sleeps (time_sleep_until). However a sleeping process/script can not be signaled to stop. Thus e.g. ⌃C will not work until the script wakes from sleep.
-
So the instead of sleeping the script will take short naps of ≤0.5s until the target time has been reached. Thus any signal to the process will take 0.5s at most to be processed.
We want the run interval to be constant no matter the actual runtime of the action. In other words, we do not want there to be any significant drift.-
In case the runtime of the action happens to be longer than than the interval the script should just skip to the next interval. So it makes a best effort at performing the action at each interval but is tolerant if that fails due to time overruns.
The script does need to use the PHP pcntl extension for the signal handling code.-
Please note that this extension is considered to be a potential security risk when used with PHP code that is executed from a web server. So you should make sure that the
php.ini
used for the web server does not include this extension. -
For a CLI script, like the one we are talking about here, it is fine though, as long as you take care with the permissions, etc. (which you should in any case).
Explaining all of this to someone who can read and unterstand code, even modify it, but who is not an actual software developer, seemed complicated. So I decided on building some heavily commented sample code to illustrate the concepts and as a potential starting point for useful scripts based on this concept. You can find it here: https://github.com/fiwswe/simpleservice
blog/simpleservice.txt · Last modified: by fiwswe
-