<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace app\crm\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Runcron extends Command{

    protected function configure()
    {
        
        $this->setName('runcron')->setDescription('Suxuan system service: every minute execute task');
    }
    
    protected function execute(Input $input, Output $output)
    {
        /**
         *要操作的类，此类必须在LIB下面
         * 
         */
        $controller = 'ListenRedis';
        /**
         * 类里的方法
         */
        $method = 'runcurn';
        
        if(!class_exists('app\\crm\\lib\\'.ucwords($controller))){
            echo '没有发现这个类：'.$controller."\r\n";
            exit();
        }
        $instance = new \ReflectionClass('app\\crm\\lib\\'.ucwords($controller));
        if (!$instance->hasMethod($method)) {
            echo '没有发现这个方法：'.$method."\r\n";
            exit();
        }

        $objMethod = $instance->getMethod($method);
        $handle = $instance->newInstance();
        $startVersion = md5_file(APP_PATH.'const.php');
        while (1){
            $dbData = db()->master()->query("select sysdate() as time");
            echo "Start new loop run at ".date('Y-m-d H:i:s').",dbDate:".$dbData[0]['time']."\r\n";
            try{
                $objMethod->invokeArgs($handle, array($this->apiParams,  $this->appId));
                $nowVersion = md5_file(APP_PATH.'const.php');
                if($nowVersion != $startVersion){
                    //防止应用升级后，忘记重启服务的情况
                    //版本发生变化，直接停止服务，让守护进程来重启
                    die;
                }
            }  catch (\Exception $e){
                if(!file_exists(ROOT_PATH.DS.'runtime'.DS.'log'.DS.  date('Ym'))){
                    mkdir(ROOT_PATH.DS.'runtime'.DS.'log'.DS.  date('Ym'),0777,true);
                }
                file_put_contents(ROOT_PATH.DS.'runtime'.DS.'log'.DS.  date('Ym').DS.'rundfp.log', date('Y-m-d H:i:s')."\t".'run error '.$e->getMessage().  json_encode($e->getTraceAsString()),FILE_APPEND);
                sleep(1);
            }
            sleep(60);
        }
        
    }

}