I’m trying to write a PHP script that will allow the user to choose both a time interval and number of iterations for running a task. I would prefer not to just leave the PHP script open for the whole time. I’m running Ubuntu, so I’ve looked at Cron and figured out how to start a job from PHP, but I’m not sure how to stop it after it has run the required amount of times. Any ideas?
Share
Your cron would simply read a DB driven queue for these requests.
So supposing the user selected a task and said at midnight, run 3 times, your php script would insert that request in a queue for the cron to check – say every minute. You could insert each iteration as a separate queue item or have the iterations as a column in the DB…
and say a row looks like this:
every minute your cron would search the DB for tasks with a status of “pending” and also is scheduled for this datetime then loop through the results and do something like so…
this also assumes task is a defined function. If not, then you fill in the blanks since we don’t know exactly what you’re doing.
SO
In order to achieve what you wanted in the comment below you would have your post script call the cron immediately upon inserting into the database – AND if you have a large user base or expect the queue to be populated then you would add a method that pretty much forces the item to the front of the cron or bypasses the queue entirely.
The general idea here is that your options are so vast in this case that it is up to you to decide HOW to handle the requests and data. For example, you could store a serialized array of the user’s parameters…
then have your cron use the contents of this array to decide how to push the requests. You don’t need to limit it to one cron too. You can have one nearly continuously running – like every 10 seconds – that just grabs the next request and does it.
So from me, the answer I have is vague in that I would definitely use crons to do this. NOT leave a script running on the client side cause that can be really bad.
But cron jobs are just like all PHP. You likely need shell access to set one up, but in the end it’s just a server task that calls a script on your server every x seconds or at a certain time regularly.