結(jié)合設(shè)計(jì)經(jīng)驗(yàn)與營(yíng)銷實(shí)踐,提供有價(jià)值的互聯(lián)網(wǎng)資訊
發(fā)布日期:2022-12-02瀏覽次數(shù):72 來源:福州網(wǎng)站建設(shè) 標(biāo)簽: tp6 timer 定時(shí)任務(wù)
composer require workerman/workerman創(chuàng)建 Timer 命令php think make:command Timer實(shí)現(xiàn) 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(守護(hù)進(jìn)程)方式啟動(dòng)')
->addOption('i', null, Option::VALUE_OPTIONAL, '多長(zhǎng)時(shí)間執(zhí)行一次')
->setDescription('開啟/關(guān)閉/重啟 定時(shí)任務(wù)');
}
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);
//創(chuàng)建定時(shí)器任務(wù)
$task = new Worker();
$task->count = 1;
$task->onWorkerStart = [$this, 'start'];
$task->runAll();
}
public function stop()
{
//手動(dòng)暫停定時(shí)器
\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秒執(zhí)行一次
try {
$now = time();
foreach ($task as $sec => $time) {
if ($now - $time >= $sec) {
//每隔$sec秒執(zhí)行一次
$task[$sec] = $now;
}
}
} catch (\Throwable $e) {
}
});
}
}Timer 參數(shù)說明Usage:
timer [options] [--] <status>
Arguments:
status start/stop/reload/status/connections
Options:
--d daemon(守護(hù)進(jìn)程)方式啟動(dòng)
--i[=I] 多長(zhǎng)時(shí)間執(zhí)行一次,可以精確到0.001注冊(cè) Timer 命令 'commands' => [
//定時(shí)任務(wù)命令
'timer'=>\app\command\Timer::class,
],啟動(dòng)定時(shí)器 php think timer start關(guān)閉定時(shí)器 php think timer stop-----以上是由福州網(wǎng)站建設(shè)的小編為你分享了"手把手教你在tp6中實(shí)現(xiàn)毫秒級(jí)定時(shí)任務(wù)功能"文章,如果你在這方面有什么問題,隨時(shí)聯(lián)系我們