<?php
/*
 * @Author: llbjj
 * @Date: 2022-07-06 16:18:19
 * @LastEditTime: 2022-07-12 18:04:12
 * @LastEditors: 863465124 863465124@qq.com
 * @Description: 
 */
namespace Application\Command\Swoole\Server;

use Application\Command\BasicCommand;
use Application\Common\Com;
use Swoole\Process;
use Swoole\Server;
use Swoole\Timer;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class SwTimerCommand extends BasicCommand {
    protected static string $commandName = 'sw:timer';
    protected InputInterface $input;
    protected OutputInterface $output;

    protected function configure()
    {
        $this->setName(self::$commandName);
        $this->addOption('sv', '', InputOption::VALUE_REQUIRED, 'Server Name');
        $this->addOption('method', '', InputOption::VALUE_REQUIRED, 'Server Method');
        $this->addOption('second', '', InputOption::VALUE_REQUIRED, '任务间隔时间');
        $this->addOption('startSecond', '', InputOption::VALUE_REQUIRED, '任务启动时间');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->input = $input;
        $this->output = $output;

        if($this->input->getOption('startSecond')) {
            $this->afterTimer();
        }else {
            $this->swTimer();
        }
        return 0;
    }

    protected function afterTimer() {
        swoole_timer_after($this->input->getOption('startSecond'), function() {
            $this->swTimer();
        });
    }

    public function swTimer() {
        swoole_timer_tick($this->input->getOption('second'), function() {
            echo date('Y-m-d H:i:s') . ' -> ' . $this->input->getOption('sv') . ' : ' . $this->input->getOption('method') . PHP_EOL;
            $this->LocalService()->{$this->input->getOption('sv')}->{$this->input->getOption('method')}();
        });
    }


    /**
     * @Description: 开启一个定时任务信息
     * @Author: llbjj
     * @Date: 2022-07-11 14:47:30
     * @param {*} $timer
     * @param {*} $timerName
     */    
    protected function setTimerFun(array &$timer, string $timerName) {
        \Swoole\Timer::tick($timer['msec'], function(int $timer_id) use($timer, $timerName){
            $timerContent = date('Y-m-d h:i:s')." 开始定时任务【{$timerName}】".PHP_EOL;
            Com::writeFile("{$timerName}.log", APP_PATH."/data/log/swooleTimer/{$timerName}/", $timerContent);
            $this->LocalService()->{$timer['serviceName']}->{$timer['funName']}();
            $nowTime = time();
            if(!empty($timer['endTime']) and $nowTime > strtotime($timer['endTime'])){
                \Swoole\Timer::clear($timer_id);
            }
        });
    }
    
}
