Meryvn
Meryvn

Reputation: 65

Execute script at intervals in php

i would like to execute a script every 2 minutes until i close the window.My script am executing every 2 minutes writes to a file. My script is not writing to the file. please see my interval script.

<?php
$interval = 1; //minutes
set_time_limit (0);
while (true)
{
  $now=time ();
  echo $now . "<BR>";
  sleep ($interval * 1 - (time () - $now));
}
?>

Upvotes: 3

Views: 9494

Answers (5)

Apostolos
Apostolos

Reputation: 3445

sleep() is definitely not the solution (I wonder why is is even considered here ...) After a lot of experimenting I have arrived to the following solution: Execute "timed" PHPs (i.e. executed at intervals) via an HTML file containing a javascript timer and a frame:

<html>
<head>
<script type='text/javascript'>
var obj;
var interval = {interval_msecs}; 
var PHP_to_execute = "http://localhost/Work/{yourPHP}.php";  
var timer = setInterval(function(){exec()}, interval);
function exec() {
  obj = document.getElementById("PHParea");
  obj.src = PHP_to_execute;
} 
</script>
</head>
<body>
<iframe id="PHParea" src=""></iframe>
</body>
</html>

This is the basis (using a localhost). You can add whaterever feature you want to it.

Upvotes: 1

mikeg
mikeg

Reputation: 11

<?php
set_time_limit(0);

$interval=1; //minutes
echo str_repeat(" ", 1024);
while(true) {
    $now=time();
    echo $now."<BR>";
    sleep($interval * 60);
    flush();
}
?>

Upvotes: 0

user133408
user133408

Reputation:

sleep takes as param number of seconds so you should write sleep($interval * 60)

Upvotes: 2

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

You probably need to add flush() after each echo. Also sleep want time in seconds, not in minutes, so your $interval should probably be set to 60 rather than to 1.

Upvotes: 1

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

Try

<?php
function do_stuff(){

  // do something

 sleep(20); // wait 20 seconds
 do_stuff(); // call this function again
}
?>

Upvotes: 4

Related Questions