請教大佬們,crontab動態(tài)操作更好的方法
我現(xiàn)在是基于Timer實現(xiàn)的,不知道各位有啥好的方法推薦
下面是我的代碼
<?php
namespace app\process;
use app\admin\logic\system\SystemCrontabLogic;
use Workerman\Crontab\Crontab;
use Workerman\Timer;
class Task
{
protected $crontab=[];
public function onWorkerStart($worker)
{
$this->init();
$this->heartBeat();
}
public function init()
{
$logic = new SystemCrontabLogic();
$taskList = $logic->where('status', 1)->select();
$allTaskKeys =[];
foreach ($taskList as $task){
if(!isset($this->crontab[$task->id])){
$crontab = new Crontab($task->rule, function () use ($logic, $task) {
$logic->run($task->id);
},$task->name);
$this->crontab[$task->id] = $crontab;
}
$allTaskKeys[$task->id] = $task->id;
}
$tasks = array_keys($allTaskKeys);
foreach ($this->crontab as $key=>$task) {
if (!in_array($key, $tasks)) { //已經(jīng)從數(shù)據(jù)庫刪除
$crontab = $this->crontab[$key];
$crontab->remove($task->getId());
unset($this->crontab[$key]);
}
}
}
public function run($args)
{
$list = Crontab::getAll();
foreach ($list as $item){
var_dump('任務(wù)ID=>'.$item->getId().'任務(wù)名稱=>'.$item->getName());
}
echo '任務(wù)調(diào)用:'.date('Y-m-d H:i:s')."\n";
// var_dump('參數(shù):'. $args);
}
private function heartBeat()
{
Timer::add(60, function () {
echo '心跳檢測:'.date('Y-m-d H:i:s')."\n";
$this->init();
});
}
}
看看有沒有參考價值(Controller里面寫的)
//查詢表中cron
$info = $this->model->where('id',$id)->select(['id',"cron",'product_ids'])->first();
$task_id = $info->id;
$old_cron = $info->cron;
//新的cron與舊cron比較
if (empty($cron) || $cron == $old_cron){
$cron = $old_cron;
}
if($cron != $old_cron){
$cron_data_task = new Crontab($old_cron,function ()use(&$cron_data_task){
$cron_data_task->destroy();
});
}
$product_ids = $info->product_ids;
$cron_data = new Crontab($cron, function () use (&$cron_data,$product_ids, $task_id,$status,$cron) {
$new_cron = IotThingsEventSource::query()->where('id',$task_id)->value('cron');
$old_cron = $cron_data->getRule();
if ($status==0 || $online_status==0 || $new_cron!=$old_cron){
$cron_data->destroy();
}else{
//執(zhí)行業(yè)務(wù)邏輯
}
});