diff --git a/examples/shutdown.php b/examples/shutdown.php new file mode 100644 index 0000000..1fb79a9 --- /dev/null +++ b/examples/shutdown.php @@ -0,0 +1,36 @@ +isRunning()) { - throw new \Error("Can't swap the event loop driver while the driver is running"); + if (isset(self::$driver)) { + if (self::$driver->isRunning()) { + throw new \Error("Can't swap the event loop driver while the driver is running"); + } + } else { + \register_shutdown_function(self::onShutdown(...), 0); } try { @@ -67,6 +71,29 @@ protected function now(): float } } + private static function onShutdown(int $invocationCount): void + { + \gc_collect_cycles(); + + $driver = self::getDriver(); + + $pending = false; + foreach ($driver->getIdentifiers() as $identifier) { + if ($driver->isEnabled($identifier) && $driver->isReferenced($identifier)) { + $pending = true; + break; + } + } + + if ($pending) { + $driver->run(); + } + + if (!$invocationCount++ || $pending) { + \register_shutdown_function(self::onShutdown(...), $invocationCount); + } + } + /** * Queue a microtask. *