构建一个定时任务管理后台

构建一个定时任务管理后台

实现一个调度定时任务的功能,不需要每次在linux 钟每次要做定时任务时就要在linux上注册任务(挂任务)。

实现如下:

创建一个专门管理定时任务的表


CREATE TABLE `tb_crontab` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL COMMENT '定时任务名称',
  `route` varchar(50) NOT NULL COMMENT '任务路由',
  `crontab_str` varchar(50) NOT NULL COMMENT 'crontab格式',
  `switch` tinyint(1) NOT NULL DEFAULT '0' COMMENT '任务开关 0关闭 1开启',
  `status` tinyint(1) DEFAULT '0' COMMENT '任务运行状态 0正常 1运行中 2任务报错',
  `last_rundate` datetime DEFAULT NULL COMMENT '任务上次运行时间',
  `next_rundate` datetime DEFAULT NULL COMMENT '任务下次运行时间',
  `execmemory` decimal(9,2) NOT NULL DEFAULT '0.00' COMMENT '任务执行消耗内存(单位/byte)',
  `exectime` decimal(9,2) NOT NULL DEFAULT '0.00' COMMENT '任务执行消耗时间',
  PRIMARY KEY (`id`)
) 

crontab表的status字段,巧用乐观锁。

实现原理: 当任务判断为可以运行时就把就把定时任务状态调用update方法,改为1, 成功rue,失败false, 只有true的任务才能执行,反之跳过

说一下自己遇到的一些坑, 例如服务器断电或者挂了, 那么就会导致一些进行中的任务状态没改成正常, 所以,断电了就要把定时任务的状态都恢复成正常

所有任务通过一个入口方法来调度


* * * * * cd /server/webroot/yii-project/ && php yii crontab/index

实现任务调度控制器 commands/CrontabController.php

<?php
namespace app\commands;

use Yii;
use yii\console\Controller;
use yii\console\ExitCode;
use app\common\models\Crontab;

/**
 * 定时任务调度控制器
 * @author jlb
 */
class CrontabController extends Controller
{

    /**
     * 定时任务入口
     * @return int Exit code
     */
    public function actionIndex()
    {
    	$crontab = Crontab::findAll(['switch' => 1]);
    	$tasks = [];

    	foreach ($crontab as $task) {

    		// 第一次运行,先计算下次运行时间
    		if (!$task->next_rundate) {
    			$task->next_rundate = $task->getNextRunDate();
    			$task->save(false);
    			continue;
    		}

    		// 判断运行时间到了没
    		if ($task->next_rundate <= date('Y-m-d H:i:s')) {
                $tasks[] = $task;
    		}
    	}

        $this->executeTask($tasks);

        return ExitCode::OK;
    }
    
    private function executeTask(array $tasks)
    {
        if (empty($tasks)) {
            return;
        }

        shuffle($tasks);

        $pool = [];
        $startExectime = $this->getCurrentTime();
        $pid = getmypid();
        $startDate = date('Y-m-d H:i:s');

        foreach ($tasks as $k => $task) {
            // 乐观锁, 上锁. 防止同一任务,重复执行, 
            $task->status = 1;
            $isOk = $task->update(false); 
            if ($isOk) {
                Yii::info("pid[$pid] 定时任务启动: {$task->name}, route: {$task->route}");
                $pool[$k] = proc_open("php yii $task->route", [], $pipe);
            }
        }

        // 防止同一任务,在多个机器上,重复执行
        sleep(self::WAIT_SYNC_TIME);

        // 回收子进程
        while (count($pool)) {
            foreach ($pool as $i => $result) {
                $etat = proc_get_status($result);
                if($etat['running'] == FALSE) {
                    proc_close($result);
                    unset($pool[$i]);

                    $tasks[$i]->exectime     = round($this->getCurrentTime() - $startExectime - self::WAIT_SYNC_TIME, 2);
                    $tasks[$i]->last_rundate = $startDate;
                    $tasks[$i]->next_rundate = $tasks[$i]->getNextRunDate();
                    $tasks[$i]->status       = '0';

                    // 任务出错
                    if ($etat['exitcode'] !== ExitCode::OK) {
                        $tasks[$i]->status = 2;
                    }
                    $tasks[$i]->save(false);
                }
            }
        }

    }

    private function getCurrentTime ()  {  
        list ($msec, $sec) = explode(" ", microtime());  
        return (float)$msec + (float)$sec;  
    }
   
}

实现crontab模型common/models/Crontab.php 没有则自己创建

<?php
namespace app\common\models;

use Yii;
use app\common\helpers\CronParser;

/**
 * 定时任务模型
 * @author jlb
 */
class Crontab extends \yii\db\ActiveRecord
{
     const WAIT_SYNC_TIME = 5; //定义这个全局量,是为了保证所有服务器的服务器时间一致
    

	/**
	 * switch字段的文字映射
	 * @var array
	 */
	private $switchTextMap = [
		0 => '关闭',
		1 => '开启',
	];

	/**
	 * status字段的文字映射
	 * @var array
	 */
	private $statusTextMap = [
		0 => '正常',
		1 => '任务保存',
	];

    public static function getDb()
    {
       #注意!!!替换成自己的数据库配置组件名称
        return Yii::$app->tfbmall;
    }
    /**
     * 获取switch字段对应的文字
     * @author jlb
     * @return ''|string
     */
    public function getSwitchText()
    {
    	if(!isset($this->switchTextMap[$this->switch])) {
    		return '';
    	}
    	return $this->switchTextMap[$this->switch];
    }

    /**
     * 获取status字段对应的文字
     * @author jlb
     * @return ''|string
     */
    public function getStatusText()
    {
    	if(!isset($this->statusTextMap[$this->status])) {
    		return '';
    	}
    	return $this->statusTextMap[$this->status];
    }

    /**
     * 计算下次运行时间
     * @author jlb
     */
    public function getNextRunDate()
    {
    	if (!CronParser::check($this->crontab_str)) {
    		throw new \Exception("格式校验失败: {$this->crontab_str}", 1);
    	}
    	return CronParser::formatToDate($this->crontab_str, 1)[0];
    }

}

一个crontab格式工具解析类common/helpers/CronParser.php

<?php
namespace app\common\helpers;

/**
 * crontab格式解析工具类
 * @author jlb <497012571@qq.com>
 */
class CronParser
{

    protected static $weekMap = [
        0 => 'Sunday',
        1 => 'Monday',
        2 => 'Tuesday',
        3 => 'Wednesday',
        4 => 'Thursday',
        5 => 'Friday',
        6 => 'Saturday',
    ];

    /**
     * 检查crontab格式是否支持
     * @param  string $cronstr 
     * @return boolean true|false
     */
    public static function check($cronstr)
    {
        $cronstr = trim($cronstr);

        if (count(preg_split('#\s+#', $cronstr)) !== 5) {
            return false;
        }

        $reg = '#^(\*(/\d+)?|\d+([,\d\-]+)?)\s+(\*(/\d+)?|\d+([,\d\-]+)?)\s+(\*(/\d+)?|\d+([,\d\-]+)?)\s+(\*(/\d+)?|\d+([,\d\-]+)?)\s+(\*(/\d+)?|\d+([,\d\-]+)?)$#';
        if (!preg_match($reg, $cronstr)) {
            return false;
        }

        return true;
    }

    /**
     * 格式化crontab格式字符串
     * @param  string $cronstr
     * @param  interge $maxSize 设置返回符合条件的时间数量, 默认为1
     * @return array 返回符合格式的时间
     */
    public static function formatToDate($cronstr, $maxSize = 1) 
    {

        if (!static::check($cronstr)) {
            throw new \Exception("格式错误: $cronstr", 1);
        }

        $tags = preg_split('#\s+#', $cronstr);

        $crons = [
            'minutes' => static::parseTag($tags[0], 0, 59), //分钟
            'hours'   => static::parseTag($tags[1], 0, 23), //小时
            'day'     => static::parseTag($tags[2], 1, 31), //一个月中的第几天
            'month'   => static::parseTag($tags[3], 1, 12), //月份
            'week'    => static::parseTag($tags[4], 0, 6), // 星期
        ];

        $crons['week'] = array_map(function($item){
            return static::$weekMap[$item];
        }, $crons['week']);

        $nowtime = strtotime(date('Y-m-d H:i'));
        $today = getdate();
        $dates = [];
        foreach ($crons['month'] as $month) {
            // 获取单月最大天数
            $maxDay = cal_days_in_month(CAL_GREGORIAN, $month, date('Y'));
            foreach ($crons['day'] as $day) {
                if ($day > $maxDay) {
                    break;
                }
                foreach ($crons['hours'] as $hours) {
                    foreach ($crons['minutes'] as $minutes) {
                        $i = mktime($hours, $minutes, 0, $month, $day);
                        if ($nowtime > $i) {
                            continue;
                        }
                        $date = getdate($i);

                        // 解析是第几天
                        if ($tags[2] != '*' && in_array($date['mday'], $crons['day'])) {
                            $dates[] = date('Y-m-d H:i', $i);
                        }

                        // 解析星期几
                        if ($tags[4] != '*' && in_array($date['weekday'], $crons['week'])) {
                            $dates[] = date('Y-m-d H:i', $i);
                        }

                        // 天与星期几
                        if ($tags[2] == '*' && $tags[4] == '*') {
                            $dates[] = date('Y-m-d H:i', $i);
                        }

                        
                        if (isset($dates) && count($dates) == $maxSize) {
                            break 4;
                        }
                    }
                }
            }
        }

        return array_unique($dates);
    }
    /**
     * 解析元素
     * @param  string $tag  元素标签
     * @param  integer $tmin 最小值
     * @param  integer $tmax 最大值
     * @throws \Exception
     */
    protected static function parseTag($tag, $tmin, $tmax)
    {
        if ($tag == '*') {
            return range($tmin, $tmax);
        }

        $step = 1;
        $dateList = [];

        if (false !== strpos($tag, '/')) {
            $tmp = explode('/', $tag);
            $step = isset($tmp[1]) ? $tmp[1] : 1;
            
            $dateList = range($tmin, $tmax, $step);
        }
        else if (false !== strpos($tag, '-')) {
            list($min, $max) = explode('-', $tag);
            if ($min > $max) {
                list($min, $max) = [$max, $min];
            }
            $dateList = range($min, $max, $step);
        }
        else if (false !== strpos($tag, ',')) {
            $dateList = explode(',', $tag);
        }
        else {
            $dateList = array($tag);
        }

        // 越界判断
        foreach ($dateList as $num) {
            if ($num < $tmin || $num > $tmax) {
                throw new \Exception('数值越界');
            }
        }

        sort($dateList);

        return $dateList;
    }
}

大功告成

创建一个用于测试的方法吧 commands/tasks/TestController.php

<?php
namespace app\commands\tasks;

use Yii;
use yii\console\Controller;
use yii\console\ExitCode;

class TestController extends Controller
{
    /**
     * @return int Exit code
     */
    public function actionIndex()
    {
		sleep(1);
        echo "我是index方法\n";
        return ExitCode::OK;
    }

    /**
     * @return int Exit code
     */
    public function actionTest()
    
    {
		sleep(2);
        echo "我是test方法\n";
        return ExitCode::OK;
    }

}

还记得一开始就创建好的crontab表吗,手动在表添加任务如下
在这里插入图片描述

进入yii根目录运行 php yii crontab/index即可看到效果.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值