- usleep: documentation ( source)
<?php
class Sleep
{
protected ?int $pending = null;
public function __construct(int $duration)
{
$this->pending = $duration;
}
public static function for(int $duration): static
{
return new static($duration);
}
public function one(): static
{
$this->pending = 100;
return $this;
}
public function two(): static
{
$this->pending = 200;
return $this;
}
public function __destruct()
{
if ($this->pending > 0) {
echo 'Sleeping for ' . $this->pending . ' μseconds' . PHP_EOL;
echo PHP_EOL;
usleep($this->pending);
}
}
}
function check(bool $a)
{
$sleep = (new Sleep(2))->one();
if ($a) {
$sleep->two();
}
// author expecting two seconds or one minute to be slept before calling next line:
echo 'CHECK:' . (new DateTime())->format(DateTimeInterface::ATOM);
echo PHP_EOL;
}
echo 'OUTER_TIME: ' . (new DateTime())->format(DateTimeInterface::ATOM);
echo PHP_EOL;
check(false);
echo 'OUTER_TIME: ' . (new DateTime())->format(DateTimeInterface::ATOM);
echo PHP_EOL;
check(true);
echo 'OUTER_TIME: ' . (new DateTime())->format(DateTimeInterface::ATOM);
echo PHP_EOL;
// expected output:
//OUTER_TIME: 2023-12-12T20:26:28+01:00
//Sleeping for 100 μseconds
//CHECK:2023-12-12T20:26:28+01:00
//
//OUTER_TIME: 2023-12-12T20:26:28+01:00
//Sleeping for 200 μseconds
//CHECK:2023-12-12T20:26:28+01:00
//
//OUTER_TIME: 2023-12-12T20:26:28+01:00