I want to use date() function in while loop of PHP but I'm getting an error as
Fatal error: Maximum execution time of 500 seconds exceeded.
I tried to set the execution time more than the time required for the loop to complete, yet it isn't working as expected.
<?php
ini_set('max_execution_time',500);
print date("H:i");
while(date("H:i")!="16:50"){
$i=0;
}
if(date("H:i")=="16:50"){
$file = "buttonStatus.txt";
$handle = fopen($file,'w+');
$onstring = "ON";
fwrite($handle,$onstring);
fclose($handle);
$i=1;
}
echo $i;
?>
This code:
while(date("H:i")!="16:50"){
$i=0;
}
Does nothing but create an infinite loop, there is no way to exit it unless the time reaches the set time. It will literally just loop constantly and never reach the code below it.
If you want to run this script at 16:50 everyday you would be better using a cron task/job. A cron is a task that is run repeatedly, it could be every few minutes, every week, month.. whatever you need.
If you can explain what you are trying to achieve here I can give you a better solution.
Related
I'm writing a function that supposed to update the price for all woocommerce products.. the price data i will get from amazon using amazon api which has a certain x query per second limit thats why i will have to sleep on each loop. Im planing to run that function as a cron job. the below function is just an example for what im planing to do so please ignore he missing variable declaration etc..
I understand that i can increase the php timeout limit but im imagining what if i have hundreads or thousand of products and on each query i will have to to sleep for a while to avoid query throtling so to update all products it can take hours in this case so im wondering what is the best and easiest solution to keep that function looping for hours and stop after reaching the last id on $products_ids array?
function text(){
foreach ($products_ids as $products_id) {
//apm_single_lookup func do an API call which has max query/sec limit thats why i added the next sleep
$lookup_data = apm_single_lookup($eu_asin, $amazon_domain);
update_post_meta($products_id, $field_name, esc_attr($lookup_data['price']));
sleep(1);
}
}
You can change max_execution_time of the server.
Or use :
http://php.net/manual/fr/function.set-time-limit.php
like this :
set_time_limit(3600);
function text(){
...
}
Or another solution :
Split your loop in multiple Ajax call (or cronjobs), so you can stop and go and do what you want.
Like this:
function text(){
foreach ($products_ids as $products_id) {
set_time_limit(60); //timelimit per loop iteration
//apm_single_lookup func do an API call which has max query/sec limit thats why i added the next sleep
$lookup_data = apm_single_lookup($eu_asin, $amazon_domain);
update_post_meta($products_id, $field_name, esc_attr($lookup_data['price']));
sleep(1);
}
//set_time_limit(5*60); //set back to longer after the loop if you want etc.
}
I think it's better in the case of loop to reset the timer on each iteration.
When called, set_time_limit() restarts the timeout counter from zero.
This way you can keep the timout small per iteration and not worry if it you have a lot of iterations. That made more sense in my head ....
It's even better to do it in the CLI (Command Line). Even when you set PHP's max execution time, Apache has it's own time limits too (likely in mod_fcgi etc).
put this code before loop:-
ini_set('max_execution_time', 0);
or
set_time_limit(0);
I am running a script which constantly works over my Database. How ever It is necessary to restart the script once an hour. Obviously I can't do that automatically. I don't want to use daemon, its too complex for me right now. Easier solution is to use cron job but biggest drawback is, it won't stop the last script. Script runs in infinite while(true) loop
However is that possible if I make function in a script, lets say
function exitScript()
{
exit;
}
And then on Cron job if i do something like
php /home/Path/public_html/webservice/myScript.php exitScript and then
php /home/Path/public_html/webservice/myScript.php
What will be the format and How can I run both one by one using cron job or make another PHP who does so?
I need advice.
Here is a little trick easy to made which you can use..
1st set you cron jobs to run on each hour.
* */1 ..... cronjob.php
2nd At start of your script define 1 constant with time:
define('SCRIPT_START_TIME', time());
3rd At your exit script set up a condition check to exit if 59 minutes are passed from this constant to current time.. :)
function exitScript()
{
if((time() - SCRIPT_START_TIME) > 59*60){
exit();
}
}
4th at each while LOOP start the exit script .
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 was expecting some error like 500 or timeout page with the following code:
<?php
ini_set('max_execution_time',5);
set_time_limit(5);
echo 'start';
sleep(10);
echo '<br/>hi';
However, I get something like this:
start
hi
Did I do something incorrect?
All I want is see the script stoped when timesout in the 5thd second, so the second echo should not be executed(I know this is quite a weird requirement)
Could anyone shred a light, thanks.
PS: seems the sleep() part is quite a distraction, how about I change the code like this:
<?php
ini_set('max_execution_time',5);
set_time_limit(5);
echo 'start';
for($i=1;$i<100000000;$i++){
if($i%100==2) echo $i;
else echo '--';
}
echo '<br/>hi';
According to this comment in php.net you must be using unix...
"Please note that, under Linux, sleeping time is ignored, but under Windows, it counts as execution time." (Sleep is not taken into consideration as part of the execution time in Unix/Linux.)
Additionally, to make it timeout simply loop forever
<?php
while (true) {
// i'll error out after max_execution_time
}
To see how long that is, you can either find out the execution time using microtime or inquire about the max_execution_time variable you just set.
$max_time = ini_get("max_execution_time");
echo $max_time
?>
UPDATE
With your updated code, the output is as expected.
Fatal error: Maximum execution time of 5 seconds exceeded in newfile.php on line 7
Is it possible to set a "callback function" that do something instead of returning an error whe the time limit is reached?
You could remove the time limit (set_time_limit(0)), and then keep track of the time the PHP script started executing and make a comparison with the current time.
<?php
$startTime = microtime();
// Whatever you need to do...
// Place this where it needs to be in the context of your application.
if (microtime() - $startTime > 15000) {
// Time's up!
}
I don't think so...that kind of defeats the point of the function to begin with... I think if you wanna do something like that, set it to 0 (no time limit) and keep track of the time a different way and do something after X time.
As others have said no.
If your script is timing out because of external factors (like it doesn't come back from a single function call), then your only remedy may be to use pcntl_alarm and pcntl_signal. Allthough I'm not sure these can be used in sapi's other then CLI.
You can Try this one :
http://www.php.net/register_shutdown_function
function shutdown()
{
// This is our shutdown function, in
// here we can do any last operations
// before the script is complete.
echo 'Script executed with success', PHP_EOL;
}
register_shutdown_function('shutdown');