| 1 |
[![Latest Stable Version]](https://packagist.org/packages/wikimedia/wait-condition-loop) [![License]](https://packagist.org/packages/wikimedia/wait-condition-loop) |
| 2 |
|
| 3 |
Wait Condition Loop for PHP |
| 4 |
=========================== |
| 5 |
|
| 6 |
This class is used for waiting on a condition to be reached, with the ability |
| 7 |
to specify a timeout. The condition is considered reached when the condition callback |
| 8 |
returns CONDITION_REACHED or true. CONDITION_ABORTED can also be used to stop the loop. |
| 9 |
|
| 10 |
Additionally, "work" callbacks can be injected to prepare useful work instead of simply |
| 11 |
having the current thread sleep or block on I/O. The loop will run one of these callbacks |
| 12 |
on each iteration of checking the condition callback, as long as there are any left to run. |
| 13 |
|
| 14 |
The loop class will automatically either retry the condition or usleep() before retrying it, |
| 15 |
depending on CPU usage. Low CPU usage and significant real-time passage is used to detect |
| 16 |
whether the condition callback appears to use blocking I/O. Use of usleep() will not occur |
| 17 |
until all of the "work" callbacks have run. This means that the condition callback can |
| 18 |
either be an "instant" CPU-bound check or a blocking I/O call with a small timeout. Both |
| 19 |
cases should automatically work without CPU intensive spin loops. |
| 20 |
|
| 21 |
Additional documentation about the library can be found on |
| 22 |
[mediawiki.org](https://www.mediawiki.org/wiki/WaitConditionLoop). |
| 23 |
|
| 24 |
|
| 25 |
Usage |
| 26 |
----- |
| 27 |
|
| 28 |
```php |
| 29 |
// Pre-compute some value that will be needed later |
| 30 |
$result = null; |
| 31 |
$workCallback = function () use ( &$result ) { |
| 32 |
$result = ( $result !== null ) ? $result : $this->doWork(); |
| 33 |
|
| 34 |
return $result |
| 35 |
} |
| 36 |
|
| 37 |
$loop = new WaitConditionLoop( |
| 38 |
function () use ( ... ) { |
| 39 |
if ( ... ) { |
| 40 |
// Condition reached; stop loop |
| 41 |
return WaitConditionLoop::CONDITION_REACHED; |
| 42 |
} |
| 43 |
// Condition not reached; keep checking |
| 44 |
return WaitConditionLoop::CONDITION_CONTINUE; |
| 45 |
}, |
| 46 |
3.0, // timeout in seconds |
| 47 |
[ $workCallback ] |
| 48 |
); |
| 49 |
$status = $loop->invoke(); // CONDITION_* constant |
| 50 |
|
| 51 |
// Call $workCallback as needed later |
| 52 |
``` |
| 53 |
|
| 54 |
Running tests |
| 55 |
------------- |
| 56 |
|
| 57 |
composer install |
| 58 |
composer test |
| 59 |
|
| 60 |
|
| 61 |
--- |
| 62 |
[Latest Stable Version]: https://poser.pugx.org/wikimedia/wait-condition-loop/v/stable.svg |
| 63 |
[License]: https://poser.pugx.org/wikimedia/wait-condition-loop/license.svg |