<?php

declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;
use app\common\api\XwCrontab;

/**
 * 主要处理短信的命令行程序
 */
class Solver extends Command {

    protected function configure() {
        // 指令配置
        $this->setName('solver')
                ->setDescription('the solver command');
    }

    protected function execute(Input $input, Output $output) {
        // 指令输出
        $lockFileName = "task_solver.lock";
        $lockFile = fopen($lockFileName, "a");
        if (flock($lockFile, LOCK_EX | LOCK_NB)) {//文件锁（独占）
            set_time_limit(0);
            $root = app()->getRootPath();
            $schedules = Db::table("new_schedule")->select();
            foreach ($schedules as $schedule) {
                //检查时间到了没
                if (XwCrontab::check(time(), $schedule["timeStr"]) && $schedule["state"] == 1) {
                    exec("php {$root}think " . $schedule["action"]);
                }
            }
            flock($lockFile, LOCK_UN);
        } else {
            $output->writeln('每分钟执行一次，执行时间超过1分钟下个1分钟跳过等待再下1分钟');
        }
    }

}
