Last active
February 23, 2023 03:19
-
-
Save arunnabraham/f83a748e3aa1a0955c3d855a72207e82 to your computer and use it in GitHub Desktop.
An example for pause and continue execution using loop/generators with ReactPHP ft Future Tick.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* An example for pause and continue execution using loop/generators with ReactPHP ft Future Tick. | |
* | |
*/ | |
require_once __DIR__ . '/vendor/autoload.php'; | |
use React\EventLoop\Loop; | |
use function React\Promise\Timer\sleep; | |
$loop = new Loop; | |
//in seconds | |
define('WAIT_TIME', 10.0); | |
define('BATCH_SIZE', 5); | |
$iterate = iterate(); | |
$batchProcess = function () use ($loop, &$batchProcess, $iterate) { | |
// time is defined based on the vaildity and entry of loop; | |
// if wait time is zero the the execution wont wait | |
$time = $iterate->current() > 1 && $iterate->valid() ? WAIT_TIME : 0; | |
// Wait or pause main execution | |
if ($time > 0) { | |
echo PHP_EOL; | |
echo '⌛ for ' . $time . ' seconds ⏲ '.PHP_EOL; | |
echo PHP_EOL; | |
} | |
sleep($time)->then(function () use ($loop, $batchProcess, $iterate) { | |
try { | |
//Run a batch process | |
while ($iterate->valid()) { | |
$current = $iterate->current(); | |
doTask($current); | |
if (invalidCondition()) { | |
//throw new Exception("invalid"); | |
} | |
if ($current % BATCH_SIZE === 0) { | |
break; | |
} | |
$iterate->next(); | |
} | |
$iterate->next(); | |
} catch (Throwable) { | |
// make invalid generator for any error | |
$iterate = fn () => yield from []; | |
} | |
if ($iterate->valid()) { | |
//Continue calling main function till the loop is valid | |
$loop->futureTick($batchProcess); | |
} | |
}); | |
}; | |
$doThis = fn () => $loop->futureTick($batchProcess); | |
//Start Process | |
$doThis(); | |
$loop->run(); | |
echo 'Process Ended!!'; | |
//Main Task | |
function iterate(): \Generator | |
{ | |
yield from range(1, (BATCH_SIZE * 2)); | |
} | |
//Child Task | |
function doTask(int $input): void | |
{ | |
printf('Running Task %s%s', $input, PHP_EOL); | |
} | |
//Condition to break loop | |
function invalidCondition(): bool | |
{ | |
return 1 !== 2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: