結合設計經驗與營銷實踐,提供有價值的互聯網資訊
composer require workerman/workerman
創建 Timer 命令php think make:command Timer
實現 Timer class Timer extends Command
{
/**
* @var int
*/
protected $timer;
/**
* @var int|float
*/
protected $interval = 2;
protected function configure()
{
// 指令配置
$this->setName('timer')
->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
->addOption('d', null, Option::VALUE_NONE, 'daemon(守護進程)方式啟動')
->addOption('i', null, Option::VALUE_OPTIONAL, '多長時間執行一次')
->setDescription('開啟/關閉/重啟 定時任務');
}
protected function init(Input $input, Output $output)
{
global $argv;
if ($input->hasOption('i'))
$this->interval = floatval($input->getOption('i'));
$argv[1] = $input->getArgument('status') ?: 'start';
if ($input->hasOption('d')) {
$argv[2] = '-d';
} else {
unset($argv[2]);
}
}
protected function execute(Input $input, Output $output)
{
$this->init($input, $output);
//創建定時器任務
$task = new Worker();
$task->count = 1;
$task->onWorkerStart = [$this, 'start'];
$task->runAll();
}
public function stop()
{
//手動暫停定時器
\Workerman\Lib\Timer::del($this->timer);
}
public function start()
{
$last = time();
$task = [6 => $last, 10 => $last, 30 => $last, 60 => $last, 180 => $last, 300 => $last];
$this->timer = \Workerman\Lib\Timer::add($this->interval, function () use (&$task) {
//每隔2秒執行一次
try {
$now = time();
foreach ($task as $sec => $time) {
if ($now - $time >= $sec) {
//每隔$sec秒執行一次
$task[$sec] = $now;
}
}
} catch (\Throwable $e) {
}
});
}
}
Timer 參數說明Usage:
timer [options] [--] <status>
Arguments:
status start/stop/reload/status/connections
Options:
--d daemon(守護進程)方式啟動
--i[=I] 多長時間執行一次,可以精確到0.001
注冊 Timer 命令 'commands' => [
//定時任務命令
'timer'=>\app\command\Timer::class,
],
啟動定時器 php think timer start
關閉定時器 php think timer stop
-----以上是由福州網站建設的小編為你分享了"手把手教你在tp6中實現毫秒級定時任務功能"文章,如果你在這方面有什么問題,隨時聯系我們