導入 workerman
php
composer require workerman/workerman
複製代碼
php think make:command 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 參數說明git
Usage:
timer [options] [--] <status>
Arguments:
status start/stop/reload/status/connections
Options:
--d daemon(守護進程)方式啓動
--i[=I] 多長時間執行一次,能夠精確到0.001
複製代碼
修改 console.php 文件github
'commands' => [
//定時任務命令
'timer'=>\app\command\Timer::class,
],
複製代碼
啓動定時器小程序
php think timer start
複製代碼
關閉定時器bash
php think timer stop
複製代碼
--------微信
高品質的開源項目, 微信商城+小程序商城: github.crmeb.net/u/giteeapp