<?php

/**
 * @desc   EasyTask 执行  php think qytask start --taskcommand timego
 * @author wolfcode
 * @url wolfcode.net
 * @支持常驻内存的PHP定时任务快捷命令
 */

namespace app\command;

use EasyTask\Task;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class QyTask extends Command
{

    protected function configure()
    {
        $this->setName('QyTask')
            ->addArgument('argv', Argument::OPTIONAL, "your argv")
            ->addOption('force', NULL, Option::VALUE_REQUIRED, 'your force')
            ->addOption('taskcommand', NULL, Option::VALUE_REQUIRED, 'your taskcommand')
            ->setDescription('芊雅专用');
    }

    protected function execute(Input $input, Output $output)
    {
        $argv        = trim($input->getArgument('argv'));
        $force       = $input->hasOption('force') ?: false;
        $taskcommand = $input->hasOption('taskcommand') ? $input->getOption('taskcommand') : "empty";
        $task        = new Task();
        switch ($taskcommand) {
            case 'timego':
                $task->addFunc(function () {
                    $now = date("Y-m-d H:i:s");
                    echo "[{$now}] It's timego now" . PHP_EOL;
                    //执行Redis 消息队列
                }, $taskcommand, 3, 2);                 // 1.添加闭包函数类型定时任务(开启2个进程,每隔10秒执行1次)
                break;
            default:
                $task->addFunc(function () {
                    $now = date("Y-m-d H:i:s");
                    echo "[{$now}] it is empty taskcommand now  " . PHP_EOL;
                }, $taskcommand, 30, 1);                 // 1.添加闭包函数类型定时任务(开启1个进程,每隔30秒执行1次)
        }
        switch ($argv) {
            case 'start':
                //初始化
                $task->start();
                // 设置非常驻内存
                $task->setDaemon(false);
                // 设置项目名称
                $task->setPrefix('EasyTask');
                // 设置记录运行时目录(日志或缓存目录)
                $task->setRunTimePath(root_path() . 'runtime' . DIRECTORY_SEPARATOR);
                $output->writeln("EasyTask start {$taskcommand}");
                break;
            case 'status':
                $task->status();
                $output->writeln("EasyTask status {$taskcommand}");
                break;
            case 'stop':
                $task->stop($force);
                $output->writeln("EasyTask stop {$force} {$taskcommand}");
                break;
            default:
                exit('argv is not exist' . PHP_EOL);
        }
        return true;
    }

}