I’m currently working on a PHP script that receives emails sent to a specific address and replies according to their content.
It’s working great, but now I need it to be executed every 10 seconds.
Here’s what I’ve tried to accomplish that:
- Using a cron job set via cpanel. It works, but even if I use >dev/null 2>&1 I get tons of logs in the root folder of my Web space, even if there are no errors; plus, the minimum interval between two executions is of 1 minute, and I’m looking for something faster
-
Using the following code:
while(true){ //my code sleep(10); }
But it doesn’t seem to work after some minutes.
What method could I use?
5
Better late than never???
Making cron execute a PHP script more often than 1 minute is not a possibility or a practical solution you should even explore.
I had a similar project that required fast polling of a target to update a database with new data. The solution for me was to create a PHP Daemon. There are plenty of tutorials about how to write a PHP Daemon so I won’t go into the specifics.
Mine was able to run every second to poll an HTTP source. This database was in turn polled every second by a Python script to update a chart on a small screen. Note, the source and polling machine were on the same local network. If you are accessing something further away, you clearly should consider the round trip and processing time when setting your Daemon sleep timer. You can then merely sleep/check for emails/transmit/sleep, etc. within a single command line PHP script rather than needlessly using cron.
Running a Damon also ensures that multiple PHP scripts aren’t operating at the same time as can be the case with fast cron job execution. I used a second script to control the startup/status/restart/shutdown of the Daemon PHP script.
I know this isn’t an exact answer with examples, but it sounds like all you needed was a recommended direction to take. Based on my experience I believe this will get you where you need to be. As mentioned in the comments there are things to consider about running a polling process on a server, but that is a matter of practice that you can keep in mind as you go.
1