<?php
/**
 * 执行计划任务
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogq <570035208@qqsina.com>
 */
 
namespace Home\Controller;
class CronController extends BaseController{
    public function _initialize(){
		$this->mod = D(CONTROLLER_NAME);
	}
    public function index(){
        $classanme=I('classanme','');
        $map['status'] = 1;
        $map['start_time'] = array("lt",NOW_TIME);
        $map['next_time'] = array("lt",NOW_TIME);
        $map['classname'] =array('neq','Popup');
        if(!empty($classanme))$map['classanme'] = $classanme;
        $order = " last_time asc ";
        $check=$this->mod->where($map)->count();
        if($check==0)die('0');
        $croninfo=$this->mod->where($map)->field('id,classname,interval_time,execute_time,start_time,is_result')->order($order)->find();
        if(empty($croninfo))die('0');
        $this->updatetime($croninfo);
        $Cron =new \Common\Vendor\Cron($croninfo['classname']);
        $data['class']=$croninfo['classname'];
        $result = $Cron->index($data); 
        if($croninfo['is_result']==1){
            $this->updateresult($result,$croninfo['id']);
        }
        die($croninfo['is_result']);
    }
    public function updateresult($result,$cron_id){//更新返回状态
        $data['remark'] = serialize($result);
        $this->mod->where("id =".$cron_id)->save($data);
        return true;
    }
    public function updatetime($croninfo){//更新时间
        $cron_id=$croninfo['id'];
        if(empty($croninfo['start_time']))$data['start_time'] = NOW_TIME;
        $data['last_time'] = NOW_TIME;
        $data['next_time'] = NOW_TIME+intval($croninfo['execute_time']*$croninfo['interval_time']);
        $this->mod->where("id =".$cron_id)->save($data);
        return true;
    }
}
?>