Function, which waits about one day in the background and then execute another.
Like:
function Sleep(){
sleep( /* One Day */ );
Run();
}
function Run(){
//One Day later,
//execute code.
}
Or maby something like this (this is fictional):
class Waiter extends Timer{
$time = 0;
function __construct($time){
$this->time = $time;
}
function onDelay(){
//One day Later.
}
}
$wait = new Waiter( /* One Day */ );
Is there a good solution?
Or is the sleep() function also okey?
But I have to say, that the execution timeout is 30 seconds.
Using a cronjob is the correct solution for this problem. If for some reason you cannot use it, make sure to add ignore_user_abort(1) and set_time_limit(0); at the top of the php script.
int ignore_user_abort ([ bool $value ] )
When running PHP as a command line script, and the script's tty goes
away without the script being terminated then the script will die the
next time it tries to write anything, unless value is set to TRUE
bool set_time_limit ( int $seconds )
Set the number of seconds a script is allowed to run. If this is
reached, the script returns a fatal error. The default limit is 30
seconds or, if it exists, the max_execution_time value defined in the
php.ini.
When called, set_time_limit() restarts the timeout counter from zero.
In other words, if the timeout is the default 30 seconds, and 25
seconds into script execution a call such as set_time_limit(20) is
made, the script will run for a total of 45 seconds before timing out.
As you said, the execution time is 30 seconds, the overall script is forced to an end after 30 seconds. It can't wait longer.
As already suggested, you could use a cron job.
If your problem is not regular recurrent, you could write a little script, which writes the time (with date) when the function should execute into a file (or a database). The cron then would execute every hour (or if its important, every minute) and checks, if the function needs to be executed
Crons have been mentioned, but there's a second option - queueing.
https://en.wikipedia.org/wiki/Message_queue
There is a wide variety of queue software available, from ones you install yourself like Beanstalk or RabbitMQ to hosted ones in the cloud like Amazon SQS or IronMQ.
Related
My website is hosted on digitalocean server and i have full control over the server. I have php script that downloads thousand of images using proxy IP. Sometimes my script takes infinite time and it slows the whole site. I checked max_execution_time and it is set to default 30 secs. But still my script doesn't stop after 30 secs. How can i stop my script from running after 2 mins so that my site doesn't effect other scripts.
The max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running.
refer this link for more details.
You can try recording the timestamp at the beginning and referencing it each iteration. Use break; or return; to exit the loop
function getImagesFromRemote($urlArray=[]) {
$start = time();
$maxduration = 3 * 60 ;
foreach ($urlArray as $url) {
// do your code
$something[] = $value;
$elapsed = time() - $start;
if ($elapsed >= $maxduration) break;
}
return $something;
}
}
By using exit() function we can stop the execution of php script. The exit() function only terminates the execution of the script. The shutdown functions and object destructors will always be executed even if exit() function is called.
I am creating an app that requires a CRON job to be executed every 60 seconds.
My host only allows a CRON job once an hour.
I was wondering if I could create a script like this:
$i = 0;
while(1==1){
// update database code
delay(10000);
// $i is incremented once a minute/10000ms
$i++;
}
//if $i reaches 60 we know that the CRON has run for an hour
if($i == 60){
die();
}
Is this recommended? Will this accurately update my database every 60 seconds?
I don't mind if the script will be a few seconds out.
I understand I will need to set my php.ini to increase the max execution time.
Should work, if the hosting allows overriding of max_execution_time.
You can do it right in the script, by the way: ini_set('max_execution_time', 0). And be careful with memory. It's not C/C++, of course, but still a good idea to watch variables initialization and loops.
In PHP, I want to put a number of second delay on each iteration of the loop.
for ($i=0; $i <= 10; $i++) {
$file_exists=file_exists($location.$filename);
if($file_exists) {
break;
}
//sleep for 3 seconds
}
How can I do this?
Use PHP sleep() function. http://php.net/manual/en/function.sleep.php
This stops execution of next loop for the given number of seconds. So something like this
for ($i=0; $i <= 10; $i++) {
$file_exists=file_exists($location.$filename);
if($file_exists) {
break;
}
sleep(3); // this should halt for 3 seconds for every loop
}
I see what you are doing... your delaying a script to constantly check for a file on the filesystem (one that is being uploaded or being written by another script I assume). This is a BAD way to do it.
Your script will run slowly. Choking the server if several users are running that script.
Your server may timeout for some users.
HDD access is a costly resource.
There are better ways to do this.
You could use Ajax. And use a timeout to call your PHP script every few seconds. This will avoid the slow script loading. And also you can keep doing it constantly (the current for loop will only run for 33 seconds and then stop).
You can use a database. In some cases database access is faster than HDD access. Especially with views and caching. The script creating the file/uploading the file can set a flag in a table (i.e. file_exists) and then you can have a script that checks that field in your database.
You can use sleep(3) which sleeps the thread for 3 seconds.
Correction sleep method in php are in seconds.
Hare are two ways to sleep php script for some period of time. When you have your code and want to pause script working for some time use these functions.
In these examples the first part of code will be done on script run and the second part of code will be done but with time delay.
Using sleep() function you can define sleep time in seconds.
Example:
echo "Message 1";
// The first part of code.
$timeInSeconds = 3;
sleep($timeInSeconds);
// The second part of code.
echo "Message 2";
This way it is possible to sleep php script for 3 seconds. Using this function you can sleep script for whole number (integer) of seconds.
Using usleep() function you can define sleep time in microseconds. This sleep time is convenient for intervals that require more precise time than one second.
Example:
echo "Message 1";
// The first part of code.
$timeInMicroSeconds = 2487147;
usleep($timeInMicroSeconds);
// The second part of code.
echo "Message 2";
You can use this function if you want to sleep php for smaller time values than second (float). In this example I have put script to sleep for 2.487147 seconds.
Have you considered using a PHP Daemon script using supervisorD. I use it in multiple tasks that are required to be running all the time.
The catch is making sure that each time you are running your script you check for memory resources. If its too high, stop the process and then let it restart itself up again.
I have successfully used this process to be always checking database records for tasks to process.
It might be overkill but worth considering.
I have a PHP script in my Code Igniter application,
its run on server and fetch some data but its not running more than 2 minutes approx..
and when I run this without using code igniter its works properly..what may be the reason behind this?
thanks #air4x its works . by setting set_time_limit(300) in the system/core/CodeIgniter.php
if (function_exists("set_time_limit") == TRUE AND #ini_get("safe_mode") == 0)
{
#set_time_limit(300);
}
after setting this code script running well..
Try adding this before you run your code: set_time_limit(0);
More info: http://php.net/manual/en/function.set-time-limit.php
If that doesn't work, you'll need to share what code you are running and what happens when it stops running.
There must be, Set_time_limit - Sets the maximum execution time of a script.
bool set_time_limit ( int $seconds )
When set_time_limit() called. It returns the counter to zero. In other words, if the default limit is 30 seconds, and after 25 seconds of script execution the set_time_limit(20) call is made, then the script will run for a total of 45 seconds before finishing .
Please visit http://php.net/manual/fr/function.set-time-limit.php for more information.
I wanted to execute a bunch of code for 5 seconds and if it has not finished executing within the specificed time frame I need to execute another piece of code..
Whether it's possible?
Ex..
There are two functions A and B
If A takes more than 30 seconds to execute the control should pass on to B
During function A you could periodically check how long the script has been executing, and if it goes over x seconds, run B:
function checkTime($start) {
$current = time();
$secondsToExecute = 5;
if (($start+$secondsToExecute) <= $current) {
func_b();
}
}
function func_a($start) {
// do some code
checkTime($start);
// do some code
checkTime($start);
// do some code
}
function func_b() {
// do something else
exit();
}
func_a(time());
http://php.net/manual/en/features.connection-handling.php
Set a time limit and a shutdown function, which checks if the status is 2 (timeout) and does your stuff if so.
One thing to note is that the time limit set this way only counts actual php processing time. Time spent with php waiting for another process or a database or http connection, etc, will not count and your time limit will not be considered reached.
If you need to count actual time that passed, even if it was not php processing time, you're going to have to go with the above suggested answer. Manually inserting that time check in places where it makes sense is the best, i.e. inside loops that you know may run too long, maybe even not on every iteration but on every N iterations, etc. Alternatively a more general approach is to use register_tick_function(), but that might lead to a noticeable performance hit with a low tick count, and you must take care to unregister it or use appropriate flags so you don't end up infinitely starting more and more calls to your timeout handling code once the timeout has happened.
Other approaches are also possible, you can register a handler for some signal using pcntl_signal() and have it sent to your process when the time limit is reached by an outside program ('man timeout' if you are on a linux box) or by a fork()-ed instance of your own php script, etc.