note 108851 added to function.time-sleep-until
| From: | rowan dot collins at cwtdigital dot com | Date: | Wed, 30 May 2012 10:42:31 +0000 |
| Subject: | note 108851 added to function.time-sleep-until | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-188293@lists.php.net to get a copy of this message | ||
Not realising that this function existed, I wrote something similar, but it has the additional
facility to specify a minimum pause even if the target time has already been reached, for instance
in a processor-intensive loop.
It's in seconds rather than microseconds (it's intended for heavy-duty CLI scripts), but
that could easily be changed by using microtime(true) and usleep if greater granularity was
required.
<?php
/**
* Pause processing until the specified time, to avoid hammering a DB or service
*
* @param int $target_time Timestamp
* @param int $min_sleep Always sleep for a minimum number of seconds,
* even if the target timestamp has already passed.
* Default 0, meaning only sleep until the target timestamp is reached.
*
* @example <code>
while ( ! $finished )
{
$minimum_start_of_next_loop = time() + $min_secs_per_loop;
# DO STUFF THAT MAY OR MAY NOT TAKE VERY LONG
sleep_until( $minimum_start_of_next_loop, $min_pause_between_loops );
}
</code>
*/
function sleep_until($target_time, $min_sleep = 0)
{
$time_now = time();
$time_to_target = $target_time - $time_now;
// If we've already reached the target time, that's fine
if ( $time_to_target <= $min_sleep )
{
// If required, sleep for a bit anyway
sleep( $min_sleep );
}
else
{
// Sleep for the number of seconds until the target time
sleep( $time_to_target );
}
}
?>
----
Server IP: 94.76.225.145
Probable Submitter: 62.189.198.114
----
Manual Page -- http://www.php.net/manual/en/function.time-sleep-until.php
Edit -- https://master.php.net/note/edit/108851
Del: integrated -- https://master.php.net/note/delete/108851/integrated
Del: useless -- https://master.php.net/note/delete/108851/useless
Del: bad code -- https://master.php.net/note/delete/108851/bad+code
Del: spam -- https://master.php.net/note/delete/108851/spam
Del: non-english -- https://master.php.net/note/delete/108851/non-english
Del: in docs -- https://master.php.net/note/delete/108851/in+docs
Del: other reasons-- https://master.php.net/note/delete/108851
Reject -- https://master.php.net/note/reject/108851
Search -- https://master.php.net/manage/user-notes.php