Delay Function PHP - 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;
}

Related

A confusion about time() function in PHP

I cannot understand why the result of subtracting the current time from the variable of $_session['now'] that has included the previous time is zero.
I expected outputting the difference between the current time and the time when i have created the variable $student->now. Explain me please.
class Student
{
public function __set($key, $value)
{
$_SESSION[$key] = $value ;
}
public function __get($key)
{
return $_SESSION[$key];
}
}
session_start();
$student = new Student() ;
//__set function will be called ;
$student->now = time();
//__get function will be called ;
echo time() - $_SESSION["now"]; // output is zero ?!
The $_session['now'] variable is set in the line before the echo.
In the echo line the current time is compared to the time set in the line before.
Because both lines are executed directly after each other, both are executed within the same second. There will be a difference of milliseconds but time() function is measured in seconds, refer to: https://www.php.net/manual/en/function.time.php.
That's why both timestamps are the same and there is no difference between these when comparing them.
time() has a precision of ONE second, you are basically doing:
$now = time(); // e.g. 1627385278
echo time() - $now; // 1627385278 - 1627385278
This happens very fast, so the output is (almost always) zero.
The fact that your example code involves a "session" hints that you want to measure time between different HTTP requests. If that is the case, some logic is needed to ONLY set the stored value for the first time, but not thereafter.

PHP Seconds to MM:SS Function

Currently I use the following javascript function to conver seconds to minutes and seconds.
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
If I pass it 235 it returns 3:55
I've tried to convert it to php, but passing 235 to it I get 55
What have I done wrong ?
function fmtMSS($s){
return($s-($s%=60))/60+(9<$s?':':':0')+$s;
};
echo fmtMSS(235);
Thanks.
You have wrong logic part in your PHP version. Take a look at this:
function fmtMSS($s){
return(($s-($s%60))/60).(9<$s?':':':0').$s%60;
};
echo fmtMSS(235);
Sandbox: http://sandbox.onlinephpfunctions.com/code/163b767d435cf9db9058d03e95b873fb07e3fcbd
There is no reason to do it in a one-liner unless its the easiest and most readable way. Don't sacrifice readable code for shorter code.
The below function is the simplest and easiest way to convert seconds into a minute:seconds format. The reason for not using date("H:i", $s) (which would yield the same result) is that it will not scale well, and return incorrect results if $s ever gets high.
Divide by 60, floor it - that will get you the minutes. Multiply it by 60 and subtract it from $s, and you have your seconds.
function fmtMSS($s){
$minutes = floor($s/60);
$seconds = $s-$minutes*60;
return "$minutes:$seconds";
};
echo fmtMSS(235); // 3:55
Live demo
The reason your original code doesn't work, is because you're using + to join strings (as you would in JavaScript). However, in PHP, one uses . to contact two strings. The logic also seems to be a bit incorrect.
<?php
function fmtMSS($s){
$min = floor($s/60);
$sec = $s%60;
return $min.':'.$sec;
};
echo fmtMSS(235);
?>
Use this code- i have just edited your function.
for short:- echo gmdate("i:s", 235);

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>

Difference among sleep() and usleep() in 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

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