Created
June 13, 2025 18:12
-
-
Save MrPunyapal/b3909ab20872bd8e1d39bcaf03f52351 to your computer and use it in GitHub Desktop.
PHP Tick-Based Timeout Wrapper (No pcntl Required)
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 | |
/** | |
* TimeoutGuard — A lightweight timeout wrapper using PHP ticks. | |
* | |
* This lets you interrupt execution of any callable if it exceeds a time limit. | |
* Works even on Windows (unlike pcntl). | |
* | |
* ⚠️ Requires `declare(ticks=1);` | |
*/ | |
declare(ticks=1); | |
class TimeoutException extends \Exception {} | |
class TimeoutGuard | |
{ | |
public static function run(callable $callback, float $seconds) | |
{ | |
$start = microtime(true); | |
// Tick handler to interrupt if time exceeded | |
$watchdog = function () use ($start, $seconds) { | |
if ((microtime(true) - $start) > $seconds) { | |
throw new TimeoutException("Execution interrupted: timeout of {$seconds}s exceeded"); | |
} | |
}; | |
register_tick_function($watchdog); | |
try { | |
return $callback(); | |
} finally { | |
unregister_tick_function($watchdog); | |
} | |
} | |
} | |
// Example usage | |
try { | |
TimeoutGuard::run(function () { | |
// Simulated heavy task | |
for ($i = 0; $i < 1e7; $i++) { | |
sqrt($i); | |
} | |
echo "✅ Task finished in time.\n"; | |
}, 0.5); // Timeout after 0.5 seconds | |
} catch (TimeoutException $e) { | |
echo "⚠️ Timeout: " . $e->getMessage() . "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment