Difference among sleep() and usleep() in PHP - php

Can any body explain me what is the difference among sleep() and usleep() in PHP.
I have directed to use following scripts to do chat application for long pulling but in this script I am getting same effect using usleep(25000); or without usleep(25000);
page1.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
type="text/javascript"></script>
<script>
var lpOnComplete = function(response) {
console.log(response);
// do more processing
lpStart();
};
var lpStart = function() {
$.post('page2.php', {}, lpOnComplete, 'json');
};
$(document).ready(lpStart);
</script>
page2.php
<?php
$time = time();
while((time() - $time) < 30) {
// query memcache, database, etc. for new data
$data = getLatest();
// if we have new data return it
if(!empty($data)) {
echo json_encode($data);
break;
}
usleep(25000);
}
function getLatest() {
sleep(2);
return "Test Data";
}
?>

The argument to sleep is seconds, the argument to usleep is microseconds. Other than that, I think they're identical.
sleep($n) == usleep($n * 1000000)
usleep(25000) only sleeps for 0.025 seconds.

sleep() allows your code to sleep in seconds.
sleep(5); // sleeps for 5 seconds
usleep() allows your code with respect to microseconds.
usleep(2500000); // sleeps for 2.5 seconds

usleep() is used to delay execution in "microseconds" while sleep() is used to delay execution in seconds.
So usleep(25000) is 0.025 seconds.
Is there any difference between the two?

One other difference is sleep returns 0 on success, false on error. usleep doesn't return anything.

Simply
usleep uses CPU Cycles while sleep does not.
sleep takes seconds as argument
while usleep takes microseconds as argument

Related

execute a script for minimum 1 second

Here is my pseudo code
For loop repeat 30 times
Call and execute API script which takes less than 1 second
I want the system to sleep for some moment(less than 1 second)
Loop end
I want the above script should finish execution in minimum of 30 seconds (2-3 seconds longer is not a problem but must not less).
Can you write a sample code for me(only time related)
Here's a little program that implements the essence of what I believe you are looking for:
$minTime = 30;
$perSec = 10000;
$start = microtime(TRUE)*$perSec;
print("This must take $minTime seconds.\n");
// Replace this loop with what you actually need done
for ($i=0; $i<10; $i++) { print("Doing stuff #{$i}... "); sleep(1); }
// Check difference in timestamps to calculate remaining time
$remain=($minTime*$perSec-(microtime(TRUE)*$perSec-$start))/$perSec;
var_dump(['remain' => $remain]);
if ($remain > 0) {
print("\n$remain seconds remaining... ");
sleep($remain);
}
print("DONE\n");
This code has been updated to use microtime() instead of time(), which only permitted intervals of integer seconds. On systems that support gettimeofday() we can work with microseconds, instead.

Using time() inside a while loop

For a school assignment we need to write a PHP script that counts for 1 second.
The following code I wrote should do exactly that was my thought:
$startTijd = time();
$teller = 0;
while($startTijd == time()){
echo 'Iteratie: ' . $teller . '<br>';
$teller++;
}
However, every time I run this or any PHP script similar to it that uses the time() function inside a while loop I get a 502 bad request from the server when I try to visit the page.
Your code as it is would not work (would not count one second exactly), because time() has a granularity of one second, and you have no guarantees that you landed on your page exactly at the tick of a second. So you need to synchronize.
To be clear, imagine calling time() several times, and let's suppose time() outputs in HH:MM:SS instead of Unix timestamps for legibility's sake:
Code
print time()
print time()
print time()
...
Output:
01:15:17
01:15:17
01:15:17
...
01:15:18
01:15:18
01:15:18
...
Your program probably currently does not work correctly because even in the little time that the loop runs, it generates a fantastic quantity of output (as can be seen above, time() remains "valid" for up to a whole second, and in that time a loop can execute lots of times). If there's some sort of resource limit on the PHP process, it's possible that this drives the process over its quota, resulting in the 502 error. You can check that by removing the echo from the loop, and just adding echo "Done." at the end.
You want to count between the instant in time in which time() transitions from 01:15:17 to 01:15:18, up to the instant when it again transitions to 01:15:19. Those instants will be separated by exactly one second.
What you would need to do is:
$startTijd = time()+1; // It is now maybe 01:15:17.93. We want to start
// counting at 01:15:18, so we need to wait for it.
while($startTijd !== time()) {
// Do nothing except maybe a very brief sleep to save CPU
usleep(5); // this is optional anyway.
}
// It is now 01:15:18.000003 and $startTijd is 01:15:18
$teller = 0;
// time() will remain equal to 01:15:18 for one second,
// while wall clock time increases from 01:15:18.000003 to 01:15:18.999999
while ($startTijd == time()) {
// Don't output anything here
$teller++;
}
// New transition detected.
// It is now e.g. 01:15:19.000137 and time() says 01:15:19.
echo 'Iteratie: ' . $teller . '<br>';
Alternately you can use microtime(true):
$teller = 0;
$endTijd = microtime(true) + 1.0;
while ($endTijd >= microtime(true)) {
// Don't output anything here
$teller++;
}
echo 'Iteratie: ' . $teller . '<br>';
Your code makes no sense... your while statment is only true if you computer is fast enough.
$startTijd = 100; # you set here the time represented by a number
while(100 == time() #101) { # here time is some milliseconds or seconds in the future
so after a second your while stops so that make not so much sense. Then use
while(true) {
and stop the while with a condition insight the while loop.

Execution time limit exceeded with PHP random number generator

I'm trying to make a program that prints a random number every 3 seconds, but my mistake is "Maximum execution time of 30 seconds exceeded", sorry but I have almost no experience in PHP and I know the functions to clear the memory, I appreciate your help .
ejemplo();
function ejemplo() {
$c=null;
$c=mt_rand(60,200);
sleep(3);
clear();
ejemplo();
}
You can use explicit flushing to load a random number every three seconds:
<?php
ob_implicit_flush(true);
ejemplo();
function ejemplo() {
$c = mt_rand(60,200);
ob_end_flush();
echo $c . "<br>\n";
ob_start();
sleep(3);
ejemplo();
}
However, you can't clear the output once it's outputted (without using JavaScript).
Another method would be to just use JavaScript:
var refresh = function() {
document.getElementById("number").innerHTML = Math.round(Math.random() * 140) + 60;
};
refresh();
setInterval(refresh, 3000);
<div id="number"></div>

Delay Function PHP

please tell me how to make a delay function to delay functions!
DelayCommand(functionToDelay, Delaytime);
..? in php 5.3+
thanks for any help
function delayCommand($callback, $delayTime) {
sleep($delayTime);
$callback();
}
This should work, consider switching out sleep() to usleep().
function DelayCommand($functionToDelay, $delayTimeInSeconds) {
sleep($delayTimeInSeconds);
$functionToDelay();
}
DelayCommand(function() { echo "yes"; }, 5);
(Code is untested)
function delayCommay($function, $nano){
usleep($nano);
$function();
}
Will do the trick however it is synchronous. So if you make a call to delayCommand it will delay your whole script until it has run the command.
If you want it done asynchronously, see my answer here: Scheduling php scripts
For your information, here's a list of related functions:
sleep() / usleep() - Sleep for an amount of (micro)seconds.
time_sleep_until() - Sleep until a timestamp.
time_nanosleep() - Sleep for an amount of seconds and nanoseconds.
Here is what I have for delaying a function in MS, Sleep and Usleep pause the execution of the whole script, this seems to work pretty well
public function DelayTime($ms){
$now = microtime();
$finishtime = ($now + $ms);
while($now < $finishtime){
$now = time();
if($now >= $finishtime){ break; }
}
return true;
}

Is there a set time out equivalent in php?

Is there a PHP equivalent to setting timeouts in JavaScript?
In JavaScript you can execute code after certain time has elapsed using the set time out function.
Would it be possible to do this in PHP?
PHP is single-threaded, and in general PHP is focused on the HTTP request cycle, so this would be tricky to allow a timeout to run code, potentially after the request is done.
I can suggest you look into Gearman as a solution to delegate work to other PHP processes.
You can use the sleep() function:
int sleep ( int $seconds )
// Delays the program execution for the given number of seconds.
Example:
public function sleep(){
sleep(1);
return 'slept for 1 second';
}
This is ugly, but basically works:
<?php
declare(ticks=1);
function setInterval($callback, $ms, $max = 0)
{
$last = microtime(true);
$seconds = $ms / 1000;
register_tick_function(function() use (&$last, $callback, $seconds, $max)
{
static $busy = false;
static $n = 0;
if ($busy) return;
$busy = true;
$now = microtime(true);
while ($now - $last > $seconds)
{
if ($max && $n == $max) break;
++$n;
$last += $seconds;
$callback();
}
$busy = false;
});
}
function setTimeout($callback, $ms)
{
setInterval($callback, $ms, 1);
}
// user code:
setInterval(function() {
echo microtime(true), "\n";
}, 100); // every 10th of a second
while (true) usleep(1);
The interval callback function will only be called after a tickable PHP statement. So if you try to call a function 10 times per second, but you call sleep(10), you'll get 100 executions of your tick function in a batch after the sleep has finished.
Note that there is an additional parameter to setInterval that limits the number of times it is called. setTimeout just calls setInterval with a limit of one.
It would be better if unregister_tick_function was called after it expired, but I'm not sure if that would even be possible unless there was a master tick function that monitored and unregistered them.
I didn't attempt to implement anything like that because this is not how PHP is designed to be used. It's likely that there's a much better way to do whatever it is you want to do.
Without knowing a use-case for your question it's hard to answer it:
If you want to send additional data to the client a bit later you can do a JS timeout on the client side with a handler that will make a new HTTP request to PHP.
If you want to schedule some task for a later time you can store that in a database and poll the DB in regular intervalls. It's not the best peforming solution but relatively easy to implement.
if ($currenturl != $urlto)
exit( wp_redirect( $urlto ) );
You can replace above two line with below code inside your function
if ($currenturl != $urlto)
header( "refresh:10;url=$urlto" );

Categories