(PECL luasandbox >= 1.4.0)
LuaSandbox::pauseUsageTimer — 暫停 CPU 使用時間計時器
暫停 CPU 使用時間計時器。
這僅在從 Lua 的回呼中呼叫時有效。當執行返回 Lua 時,計時器將自動取消暫停。如果再次呼叫 Lua,計時器將在該呼叫期間取消暫停。
如果 PHP 回呼在計時器未暫停的情況下再次呼叫 Lua,然後該 Lua 函式再次呼叫 PHP,則第二次 PHP 呼叫將無法暫停計時器。其邏輯是,即使第二次 PHP 呼叫會避免將 CPU 使用量計入限制,第一次呼叫仍然會將其計入。
此函式沒有參數。
傳回一個 bool 值,指示計時器現在是否已暫停。
範例 #1:操作使用計時器
<?php
// 建立一個新的 LuaSandbox 並設定 CPU 限制
$sandbox = new LuaSandbox();
$sandbox->setCPULimit( 1 );
function doWait( $t ) {
$end = microtime( true ) + $t;
while ( microtime( true ) < $end ) {
// 消耗 CPU 週期
}
}
// 註冊一個 PHP 回呼函式
$sandbox->registerLibrary( 'php', [
'test' => function () use ( $sandbox ) {
$sandbox->pauseUsageTimer();
doWait( 5 );
$sandbox->unpauseUsageTimer();
doWait( 0.1 );
},
'test2' => function () use ( $sandbox ) {
$sandbox->pauseUsageTimer();
$sandbox->unpauseUsageTimer();
doWait( 1.1 );
}
] );
echo "這不應該逾時...\n";
$sandbox->loadString( 'php.test()' )->call();
echo "這應該會逾時。\n";
try {
$sandbox->loadString( 'php.test2()' )->call();
echo "沒有嗎?\n";
} catch ( LuaSandboxTimeoutError $ex ) {
echo "逾時了! " . $ex->getMessage() . "\n";
}
?>
以上範例將輸出
This should not time out... This should time out. It did! The maximum execution time for this script was exceeded