yii框架php计划任务,yii2的Console定时任务创建

本文详细介绍了如何在Yii2框架中使用Console控制器实现定时任务,包括通过CRON表调度执行php脚本,以及清理MongoDB中的数据示例。重点展示了如何配置Crontab和编写清理MongoDB数据的控制器方法。
摘要由CSDN通过智能技术生成

Yii2的定时任务可以有两种写法,原理都是通过服务器的定时任务去调用

1.通过调用指定的URL访问 就相当于在浏览器中访问

2.通过console调用

下面我们就来说说Console 是如何实现定时任务的

一、首先在创建Controlle 并继承 yii\console\Controller;

namespace console\controllers;

use yii\console\Controller;

class TestController extends Controller {

public function actionIndex()

{

echo "hello world";

}

}

b2fd1dfd0d0dc73fb0e1f07cd3e59a79.png

在yii根目录下,命令行执行

yii test/index

如果是class AaaBbbController function ActionAaaBbb

yii aaa-bbb/aaa-bbb

linux下,运行

crontab -e

30 21 * * * /usr/local/php/bin/php /your_project_path/yii test/test

二、用命令行cmd测试是否成功

(一定要看好路径去执行   yii  这个文件              一定要写绝对路径)

/你的文件夹路径/yii      你的文件夹路径/console/test(控制器)/index(方法)

或者进入的你的项目目录下,例如 D:\wamp\www\smartSPACE>yii crontab/copy-db,你需要配置你的php环境变量

下例为  在console文件夹下执行控制器和方法

08e6b1d3a634009057c1f5b3916cacdd.png

三、设置定时任务

linux下,运行crontab -e

30 21 * * * /usr/local/php/bin/php /your_project_path/yii test/test

*/1 * * * * /usr/local/php/bin/php /home/wwwroot/smartSPACE/yii crontab/copydb

这里根据自己需求填写

上面的例子表示每晚的21:30执行上面的定时程序

下面是定时任务设置的一些基本介绍

基本格式 :

command

分 时 日 月 周 命令

第1列表示分钟1~59 每分钟用*或者 */1表示

第2列表示小时1~23(0表示0点)

第3列表示日期1~31

第4列表示月份1~12

第5列标识号星期0~6(0表示星期天)

第6列要运行的命令

crontab文件的一些例子:

30 21 * * * /usr/local/etc/rc.d/lighttpd restart #上面的例子表示每晚的21:30重启apache。

45 4 1,10,22 * * /usr/local/etc/rc.d/lighttpd restart #上面的例子表示每月1、10、22日的4 : 45重启apache。

10 1 * * 6,0 /usr/local/etc/rc.d/lighttpd restart #上面的例子表示每周六、周日的1 : 10重启apache。

0,30 18-23 * * * /usr/local/etc/rc.d/lighttpd restart #上面的例子表示在每天18 : 00至23 : 00之间每隔30分钟重启apache。

0 23 * * 6 /usr/local/etc/rc.d/lighttpd restart #上面的例子表示每星期六的11 : 00 pm重启apache。

0 */1 * * * /usr/local/etc/rc.d/lighttpd restart #每一小时重启apache

例子:

*/1 * * * * /usr/local/php/bin/php /home/wwwroot/smartSPACE/yii crontab/copy-db>>/home/wwwroot/smartSPACE/commands/test.txt

注释:

一分钟重复 */1 * * * *

php目录 /usr/local/php/bin/php

项目目录 /home/wwwroot/smartSPACE/

运行的方法 yii crontab/copy-db

结果值写入那个文件 /home/wwwroot/smartSPACE/commands/test.txt

linux 上跟windows类似

/usr/local/php/bin/php /home/wwwroot/smartSPACE/yii crontab/copy-db

/usr/local/php/bin/php你的linux下的php环境位置 /home/wwwroot/smartSPACE/yii crontab/copy-db你的项目目录

给个php代码例子

/**

* @ 定时任务

* @

* @

*/

namespace app\commands;

use yii\console\Controller;

// use MongoDB\BSON\ObjectID;

class CrontabController extends Controller

{

/**

* 定时清理mongodb数据

*/

public function actionClearMongo()

{

$query = new \yii\mongodb\Query();

$time_end = strtotime(date('2018-06-20'));

$time_begin = strtotime("2018-05-30");

$collection = \Yii::$app->mongodb->getCollection('publish_message');

$i = 1;

while ($time_begin < $time_end){

$date = date("Y-m-d", $time_begin);

$start_time = strtotime($date." 00:00:00");

$end_time = strtotime($date." 23:30:00");

//清除每天23:30前的数据

$where = [

"between","payload.timestamp", $start_time, $end_time

];

$time_begin +=24*3600;

// var_dump(new \MongoDB\BSON\UTCDateTime($end_time.'000'));die;

$data = $query->from('publish_message')->where($where)->orderBy('created asc')->all();

// $primaryVal = new \yii\mongodb\MongoId('000000000000000000000001');

// dump($primaryVal);die;

// $collection = \Yii::$app->mongodb->getCollection('publish_message');

// var_dump((string) new \yii\MongoDB\BSON\ObjectId('000000000000000000000001'));

// $data = $collection->find([]);

foreach ($data as $v){

// var_dump($v);

$oid = (string)$v['_id'];

echo $i.'-'.$oid.'

';

$collection->remove(['_id' => $v['_id']]);

$i++;

}

}

die;

}

/**

* 定时任务获取mondb内故障消息

* create dahai

* time 2018/07/18

*/

public function actionCopyDb(){

$query = new \yii\mongodb\Query();

//先获取上一次的结束时间

$last_result = $query->select(['end_time'])->from('timed_task')->orderBy('_id desc')->limit(1)->one();

$last_time = $last_result['end_time'];

$start_time = $last_time;

$end_time = time();

$collection = \Yii::$app->mongodb->getCollection('timed_task');

$collection->insert(['end_time' => $end_time]);

$query->andWhere([

"between","payload.timestamp", $start_time, $end_time

]);

$query->andWhere(['in', 'payload.desired.arrays.0.status.event', [1,2,3,4,5,6,7]]);

$result = $query->select(['created', 'payload'])->from('publish_message')->orderBy('created asc')->all();

if ($result){

//故障类型,设备别称,开关别称,故障时间

foreach ($result as $k => $l)

{

//对应相关用户通知故障消息

$deviceid = $l['payload']['deviceid'];

$Equipment= \app\models\Equipment::find()->select('id')->where(['serial_number'=>$deviceid])->one();

$EquipmentUser =\app\models\EquipmentUser::find()->select('user_id')->where(['equipment_id'=>$Equipment->id])->asArray()->all();

$user_ids = array_column($EquipmentUser,'user_id');

$created = $l['payload']['timestamp'] > 0 ? date('Y-m-d H:i', $l['payload']['timestamp']) : '---';

$event_desc = \app\services\VStatusLog::$event[$l['payload']['desired']['arrays'][0]['status']['event']];

//查询别名

$eAlias = \app\models\Alias::findOne(['type'=>1,'extend_id'=>$l['payload']['deviceid'],'user_id'=>$this->uid]); //设备别名

$sAlias = \app\models\Alias::findOne(['type'=>2,'extend_id'=>$l['payload']['desired']['arrays'][0]['device']['id'],'user_id'=>$this->uid]);//开关别名

$alias1 = $eAlias?$eAlias['alias']:$l['payload']['deviceid'];

$alias2 = $sAlias?$eAlias['alias']:'开关'.$l['payload']['desired']['arrays'][0]['device']['index'];

while ($user_id = array_shift($user_ids)){

$FaultMessage = new \app\models\FaultMessage();

$FaultMessage->user_id = $user_id;

$FaultMessage->message_id = ($l['_id'])->__toString();

$FaultMessage->created = $created;

$FaultMessage->event = $l['payload']['desired']['arrays'][0]['status']['event'];

$FaultMessage->event_desc = $event_desc;

$FaultMessage->equipment_alias = $alias1;

$FaultMessage->switch_alias = $alias2;

$FaultMessage->create_time = time();

$FaultMessage->save();

}

}

}else{

echo "没有".date("Y-m-d H:i:s")."\n";

return "没有东西";

}

echo "有".date("Y-m-d H:i:s")."\n";

return "有东西";

}

}

yii2中,关于你加载了一些数据库或者扩展依赖,你需要在添加config-console.php添加你在web.php相同的配置即可

例如我这个报错:yii\di\ServiceLocator->get('mongodb') yii\mongodb\Query->all()就是因为这个导致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值