php script that calls itself when it is finished - indefinately - php

I have a php script that can take anything from 2 to 10 minutes to execute. It fetches info from around the web so its time depends on how fast lots of other things are talking.
I used to run the script on a cron every 15 minutes, but sometimes it only takes 2 minutes to run.
So I wondered if I can somehow make it run perpetually - setting itself going again as soon as it finishes its task? That way, however long it takes, it will always start agaiun straight away.

Seems like you're running into cron job issues. I would instead turn your script into a daemon, that way it can run perpetually without fear of overlaps or finishing too fast.
Here's a tutorial how to do it.
http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/

Put the entire thing in an infinite loop? Either in the PHP code itself, or make a launch script that does that.

Writing a daemon is probably the best solution.
If you're lazy, and on linux/unix, you can just script an infinite loop, and set it running inside a screen session.

Related

How do I make a difficult php script (cronjob) run for a longer time to not kill the server?

I have a PHP cronjob which runs at 6:00am every day to do some calculations and store them in the SQL. What happens now is that the site becomes a bit unresponsive for about 40 seconds while the cron is running.
I was wondering whether using sleep() in the script would do the trick? Let's say I'd pause it for 2 seconds roughly every second. Therefore, the script would run for a lot longer time, but would also let apache use the system's resources.
Am I right? Does it work? Or will the script still keep resources to itself, even during the sleep()?

best way to repeat php script after fixed interval

i want my php script to be executed after every 10 seconds until stop button is pressed
Is using an while loop with sleep() the best way or there is a better way of doing it?
And i want to know that if i run that while loop, will it prevent the other scripts on the page from running?
i mean that during the sleep time, as the PHP script is still running, will browser wait for this script to end of will run other scripts simultaneously?
As far as i have understood, cron wont be helpful in this case as i have to run the script between the time when start and stop button are pressed. Please correct me if i am wrong.
Cron would do the job although, with an interval as small as 10 seconds, you'd probably be better off writing a daemon instead (and running from the command line or init.d, not through a web server).
You just need a way to switch it on and off. That could be something as simple as testing to see if a file exists (and then adding or deleting it as desired).
And i want to know that if i run that while loop, will it prevent the other scripts on the page from running?
You need to make the script stand-alone for this to make any sense at all.

scheduled PHP script execution without cron

I have a PHP script that needs to be executed by the end of every month. How would I do that without using cron on Unix-like systems or Task Scheduler on Windows systems? Isn't there some built-in feature in php for this? Because using cron/scheduler is not that much portable way IMO.
The only other way is by triggering it when the website is loaded. For example, you'd store the time the script was last run. Then every time a page is loaded, you'd check if it's time to run it. If so, then you would run it as part of the page load. Of course, this depends on (1) the task being a very quick one, and (2) that the task doesn't have to be run exactly on schedule, down to the second. This is basically how wp_cron() works in Wordpress.
Php is just a scripting language, not a process that is aware of time and may trigger events at desired moments.
Once you settle in a server, you don't have to worry about portability: migrating to another place won't be an automatic process because the environment could be very different.
So stick with cron, or write yourself a OS-agnostic layer.
In the system i worked on, i had a little module that had the last running of the script saved, and on every running of the main script, it checked, if the script shouldn't have been run. In case it should have, it did before anything else executed, so the system had the right data anyway, even if the periodical script wasn't run "on time". It also checked if the script shouldn't have been run more than once, and ran it several times, if needed.
A bit crude, but produces the right results without anything but PHP/mysql.

Sleep function on php

As a possible alternative to using cron jobs, I found the sleep function. I have never used this before.
If I tell my script to run inside a kind of loop, and inside that loop I have an instruction like this
# sleeps for 86400 seconds or one day
sleep(86400);
will my script be launched again after 1 day? even if don't access it on my web browser again within that period?
I think is not possible, but I'm here to ask an expert about it.
The main problem with using PHP this way is, in my experience, not web server timeouts (there are ways to handle that with difficulty varying on the server and the platform) but memory leaks.
Straightforward PHP code tends to leak a lot of memory; most of the scripts I wrote were able to do hundreds of times as many work after I did some analysis and placed some unsets. And I was never able to prevent all the leaks this way. I'm also told there are memory leaks in the standard library, which, if true, makes it impossible to write daemons that would run for a long time in loops.
The script will timeout. You need to set it so that it won't timeout using set_time_limit.
I wouldn't do this I would either use a cron (that is a link) job if it is a regular task or an at (that is a link) job if the job is added at the run time of your script.
cron allows you to run a recurring job every day at 1pm for example whereas at allows you to schedule a job to run once for now +1day for example.
I have written a PHP 5.3 wrapper for the at queue if you choose to go down that route. It is available on GitHub https://github.com/treffynnon/PHP-at-Job-Queue-Wrapper
There is also time_sleep_until(). Maybe more useful to wake up on a specific time...
If you access the script through a web browser, it will be terminated after 30 seconds.
If you start the PHP script on the command line, this could work.
It would work, but your "startup time" will be subject to drift. Let's say your job takes 10 seconds to run, then sleeps 86400, runs another 10, sleeps 86400, etc.. You start it exactly at midnight on day 1. On Day 2 it'll run at 12:00:10am, on day 3 it's 12:00:20am, etc...
You can do some fancy math internally to figure out how long the run took, and subtract that from the next sleep call, but at the point, why not use cron? With cron the script will exit after each run, cleaning up memory and resources used. With your sleep method, you'll have to be VERY careful that you're not leaking resources somewhere, or things will eventually grind to a halt.
I had a similar problem before and found a php cron parsing class that will allow you to execute php similar to running crons. You can tie it to a commonly accessed script on your site if you don't have access to run crons directly.
I actually use this script as part of a larger cron job script:
a cron job runs every hour
an xml file for each sub-cron with a cron-like time component(i.e.- * */2 * * * php /home..)
the sub-cron script that will run if the current time meets the criteria of the sub-cron time component
a user interface is setup so that I don't have to manually add/remove sub-crons from the main cron
The cronParser class is here.
Many correct answers, but: Using sleep() means your script keeps running, and keeps using memory. Raising the default timeout of 30s will work, but again, this is bad idea. I suggest you use crontasks.
This is why legitimate cron jobs were invented. Just use crontab. Using a PHP script to do it will be EXTRAORDINARILY unreliable, buggy, and poorly timed.
Hope this is insightful.

Cron job for php script that requires VERY long execution time

I have a php script run as a cron job that executes a set of simple tasks that loops for each user in the database and takes about 30 mins to complete. This process starts over every hour and needs to be as fast and efficient as possible. The problem Im having, is like with any server script, execution time varies and I need to figure out the best cron time settings.
If I run cron every minute, I need to stop the last loop of the script 20 seconds before the end of the minute to make sure that the current loop finishes in time. Over the course of the hour this adds up to a lot of wasted time.
Im wondering if its a bad idea to simple remove the php execution time limit and run the script once an hour and let it run to completion.... is this a bad idea?
Instead of setting the max_execution_time you could also use set_time_limit() to reset the counter on every loop. This will ensure your script is never running out of time unless there is something serious hanging within the current loop (and taking longer than the max_execution_time).
Basically this should make your script run as long as it needs while giving it a 30 seconds timeout between two set_time_limit() calls.
Assuming you'd like the work done ASAP, don't use cron. Cron is good for things that need to happen at specific times. It's often abused to simulate a background process that would ideally process work as soon as work appears. You should probably write a daemon that runs continuously. (Note: you could also look at a message/work-queue type system, there are nice libraries out there to do this too)
You can write a daemon from scratch using the pcntl functions (since you don't care about multiple worker processes, it's super-easy to get a process running in the background.), or cheat and just make a script that runs forever and run it via screen, or leverage some solid library code like PEAR's System:Daemon or nanoserv
Once the daemonization stuff is taken care of, all you really care about is having a loop that runs forever. You'll want to take care that your script doesn't leak memory, or consume too many resources.
Generally, you can do something like:
<?PHP
// some setup code
while(true){
$todo = figureOutIfIHaveWorkToDo();
foreach($todo as $something){
//do stuff with $something
//remember to clean up resources so you don't leak memory!
usleep(/*some integer*/);
}
usleep(/* some other integer */);
}
And it'll work pretty well.
Setting the time limit to 0 and letting it do its thing is fairly typical of PHP based cronjobs (in my experience), but this is also the point when you should ask yourself a few important questions, such as "Should I rewrite this job in a compiled language?" and "Am I using all of my tools (database, etc) to their maximum efficiency?"
That said, maybe better than completely removing the time limit would be to set it to the upper limit you actually want. If that means 48 minutes, then set_time_limit(48 * 60);
I really think you shouldn't set the time out to 0, that is just looking for trouble. At most, set it to 59*60 seconds, but setting it to 0 might cause security problems, if a script hangs, it will hang almost forever until the server host stops the execution. It is considered bad practice to do so.
I have used the php command-line interface for similar long running tasks in the past. You probably do not want to remove the execution time limit for any request.
Sounds like a great idea if there's little chance that it will take more than an hour. Note, however, that the wrong bug can be a really good way of making it take longer than expected..
To avoid all sorts of nasty problems, you should have a guard file with the process ID of the script. On startup, you should check to make sure the file doesn't exist, or if it does that the process ID in the file doesn't exist (through a kill( pid, 0 ) call). If these conditions are met, create a new file with the script's PID and delete the file when you're done.
This is the same trick that many daemons use to ensure it isn't already running. If the daemon was killed suddenly, the file will still exist but the PID of the process therein is unlikely to be running.
Depending on what your script does, it can lead to problems if you remove the time limit. If per example, you are polling an external server that is unresponsive while the job is running, and that your cron takes 2 hours instead of 30 minutes to complete, you may get a stack of PHP processes being fired up even if the previous ones haven't completed yet. This can cause system instability and crashes.
You probably have two options:
Make sure that no other instance of your script is running beforehand, otherwise exit() on start.
Consider changing your cronjob into a daemon.
Does it have to run hourly like clockwork?
If not split the job (you mentioned it was more than one simple task) do each task every hour?
Or split it per user, do A-M on hour, then N-Z the next?

Categories