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.
Related
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.
I'm trying to create a form just to mess around with and I there are two sections of this form. The first input is a number to count up to and the second input is a delay interval in seconds.
I have two ways of doing this. One, is to do this client side and the other is to take the variables and send them via php. This will allow the user to leave the website and have the script still working.
The issue with this being server side is that after 60 seconds, the PHP script stops working. The form is being sent via AJAX. Here is my PHP code. I'm also on shared hosting and do not have the ability to edit PHP.ini.
$amount = $_POST["amount"];
$time = $_POST["time"];
date_default_timezone_set('America/Los_Angeles');
$x = 0;
while($x < $amount) {
echo $x;
$x++;
sleep($time);
}
echo ("Counted to " . $x);
You can use max execution time on your php file, add this line in your php file.
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
You can use set_time_limit to set the max execution time, and 0 means no time limit (not recommanded for cgi, since you web server, apache/iis still have a time limit)
and if you want to change your execution time limit of all the php scripts, you can change the setting max_execution_time in the php.ini
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 to parse live scores from JSON url,then check if some scores are change it call another php script to push notifications to IOS devices.
my question is how can i make the first script run every 20 seconds.
It depends on the host OS that you're using. For linux/unix/etc. the preferred tool for scheduling tasks is cron. For Windows or Mac or anything like that there are other built-in schedulers.
Using cron, to schedule a task to run every minute might look something like this:
* * * * * /path/to/command
The granularity, however, seems to only go to the minute. So without a more granular task scheduler, you may need to internally handle the 20 second delay.
One idea could be to wrap the task in a script which runs the command, sleeps for 20 seconds, runs the command again, sleeps for 20 seconds, and runs the command again. Then the cron job would call that wrapping script. My bash is a little rusty, but the idea would look something like this:
/path/to/command
sleep 20
/path/to/command
sleep 20
/path/to/command
$total_time = 0;
$start_time = microtime(true);
while($total_time < 60)//run while less than a minute
{
//DoSomething;
echo $total_time."\n";
sleep(20);//wait amount in seconds
$total_time = microtime(true) - $start_time ;
}
add this to cronjob to run every minute.
maybe you can try sleep
while(1) {
exec('php path/to/script.php');
sleep(20);
}
Generaly a cronjob is perfect for this kind of task. Have a look at this here: http://www.thegeekstuff.com/2011/07/php-cron-job/
If that's not applicable you might be able to Script something for the PHP CLI http://php.net/manual/en/features.commandline.php which allows you unlimited runtime. Just put a while(true) loop with a sleep() in there and run it with the php command like > php yourscript.php
I'm trying to modify a csv import function which times out after 60 sec of importing. For every line there are images that are resized and some other code is executed.
I know the vps can handle this but in batches because I have another website on the same server that runs a different csv program but does the same thing. That program can import 8000 lines and resize images as well. The settings there are: process 10 lines and wait 3 sec, repeat.
Settings I raised:
set_time_limit
max_execution_time
Browser http keep alive timeout
I have tried sleep() for every 10th line but this only makes the process import fewer lines
if( (($current_line % 10) == 0) && ($current_line != 0) )
{
sleep(3);
}
This is how the script loops through the file
for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++)
{
//code here
}
Server:
Apache
PHP 5.3.3
MYSQL
Varnish cache
What can I do to make this work?
The first thing to try when your script times out is to run it using the php-cli. There is no execution time limit to scripts that are run through the command line.
If this doesn't solve your problem, then you know it wasn't the execution time limit.
The second thing to try is to print out regular status messages, including from memory_get_usage() so that you can eliminate memory leaks as a cause for your script crash. This may help you identify whether your script was dying on some input.
you can over-write the default timeout time.
set_time_limit (0) ;
using sleep will make it import fewer lines, basically the script is timeing out because it is taking over 60 seconds. by adding sleep it just gets less done in 60 seconds.
If this is a critical script i'd look at moving it to another programing language that can execute this faster. if its just a one off, or not mission critical try set_time_limit(0) which makes it never time out. also try typing php scriptname into the browser to run the script in command line.
Try outputting something to the browser to keep the browser alive. IE times out after 1 minute if inactivity FF is 3 minutes.
<?
if( (($current_line % 10) == 0) && ($current_line != 0) )
{
sleep(3);
echo '. ';
}
?>