yii框架通过控制台命令创建定时任务
假设Yii项目路径为 /home/apps
1. 创建文件 /home/apps/web/protected/commands/console.php
$yii = '/home/apps/framework/yii.php';
require_once($yii);
$configFile = dirname(__FILE__).'/../config/console.php';
Yii::createConsoleApplication($configFile)->run();
2. 修改配置文件 /home/apps/web/protected/config/console.php,配置需要的组件、数据库连接,日志等信息,格式类似主配置文件main.php
// This is the configuration for yiic console application.
// Any writable CConsoleApplication properties can be configured here.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'My Console Application',
'import'=>array(
'application.models.*',
'application.components.*',
'application.extensions.*',
),
// preloading 'log' component
'preload'=>array('log'), // application components
'components'=>array( // database settings are configured in database.php
//'db'=>require(dirname(__FILE__).'/database.php'),
'db'=>array(
//'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
// uncomment the following lines to use a MySQL database
'connectionString' => 'mysql:host=localhost;dbname=testdrive',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
),
), ),
);
3. 在 /home/apps/web/protected/commands/ 下新建 TestCommand 类,继承 CConsoleCommand,在TestCommand中,可以使用项目的配置信息和Yii的各种方法
class TestCommand extends CConsoleCommand {
public function getHelp() {
return 'test command help';
}
public function run($args) {
echo 'hello '. $arg[0];
}
}
执行命令
php console.php Test
在这个类中我们需要完成2个方法,一个是getHelp(),他用于提供Test这个类命令的帮助信息,我们可以在shell中通过命令来查看这个类的帮助
php console.php help Test
此外这个类的主要功能是通过继承 run($args) 这个方法来实现的,其中$args 为从命令行获得参数数组。
现在如果我们在屏幕上输入:php console.php Test li
我们将看到程序返回: hello li
继承CConsoleCommand写入自己的命令类,Yii提供了两种方式去执行
1. 如果你执行单一的任务,直接在run方法里面写
class CHelpCommand extends CConsoleCommand
{
/**
* Execute the action.
* @param array $args command line parameters specific for this command
*/
public function run($args)
{
$runner=$this->getCommandRunner();
$commands=$runner->commands;
if(isset($args[0]))
$name=strtolower($args[0]);
if(!isset($args[0]) || !isset($commands[$name]))
{
if(!emptyempty($commands))
{
echo "Yii command runner (based on Yii v".Yii::getVersion().")\n";
echo "Usage: ".$runner->getScriptName()." <command-name> [parameters...]\n";
echo "\nThe following commands are available:\n";
$commandNames=array_keys($commands);
sort($commandNames);
echo ' - '.implode("\n - ",$commandNames);
echo "\n\nTo see individual command help, use the following:\n";
echo " ".$runner->getScriptName()." help <command-name>\n";
}
else
{
echo "No available commands.\n";
echo "Please define them under the following directory:\n";
echo "\t".Yii::app()->getCommandPath()."\n";
}
}
else
echo $runner->createCommand($name)->getHelp();
}
/**
* Provides the command description.
* @return string the command description.
*/
public function getHelp()
{
return parent::getHelp().' [command-name]';
}
}
2. 另外一种就是同写你的Controller(控制器),前面增加actionXXX,例如:
class CleanupCommand extends CConsoleCommand {
private $sessionTableName = 'it_common_session';
/**
* Index Action
*/
public function actionIndex() {
echo "默认动作";
}
/**
* 自动执行清理Session,每2分钟.
*/
public function actionSession() {
$now = time();
$sql="DELETE FROM {$this->sessionTableName} WHERE lastactivity < $now";
$command = Yii::app()->dz->createCommand($sql);
$command->execute();
}
/**
* 清理系统缓存,每天早上7:30
*/
public function actionCache() {
Yii::app()->cache -> flush();
Yii::app()->dbcache -> flush();
Yii::app()->fcache -> flush();
}
/**
* 清除上传临时文件
*/
public function actionTempfiles() {
$dir = Yii::getPathOfAlias('site.frontend.www.uploads.temp').'/';
foreach(glob($dir.'*.*') as $v){
unlink($v);
}
}
}
执行Index动作,默认Index
php cron.php Cleanup
执行Cache动作
php cron.php Cleanup cache
4. 创建定时任务
$ crontab -e
* * * php console.php cleanup >> /path/to/logfile &
上面的意思是说每天晚上两点自动执行清理任务,简单几步就完成了强大的自动化功能任务.是不是够简单
yii框架通过控制台命令创建定时任务的更多相关文章
- Yii通过控制台命令创建定时任务
假设Yii项目路径为 /home/apps/ 1. 创建文件 /home/apps/protected/commands/crons.php <?php $yii = '/home/apps/f ...
- Yii框架学习笔记(二)将html前端模板整合到框架中
选择Yii 2.0版本框架的7个理由 http://blog.chedushi.com/archives/8988 刚接触Yii谈一下对Yii框架的看法和感受 http://bbs.csdn.net/ ...
- yii创建控制台命令
创建控制台命令程序1.控制台命令继承自 yii\console\Controller控制器类2.在控制器类中,定义一个或多个动作,动作与控制台子命令相对应3.在动作方法中实现业务需求的代码 运行控制台 ...
- YII框架的部署 通过YII脚手架程序创建应用程序系统
1,把YII框架里面的framework复制粘贴到nginx目录下 2,创建一个商城系统: 1)修改环境变量 制定php.exe的目录 2)C:\Users\Administrator>cd C ...
- Laravel 5.1 中创建自定义 Artisan 控制台命令实例教程
1.入门 Laravel通过Artisan提供了强大的控制台命令来处理非浏览器业务逻辑.要查看Laravel中所有的Artisan命令,可以通过在项目根目录运行: php artisan list 对 ...
- YII 框架使用之——创建应用
linux环境为UBUNTU14.04,YII框架的版本是1.1.17 将下载的YII解压缩,压缩后会有三个文件夹,”demos,requirements,framework”,demos 当然就是演 ...
- Laravel创建自定义 Artisan 控制台命令实例教程
来源:http://laravelacademy.org/post/1374.html 1.入门 Laravel通过Artisan提供了强大的控制台命令来处理非浏览器业务逻辑.要查看Laravel中所 ...
- Yii 框架学习--01 框架入门
Yii 是一个高性能的,适用于开发 WEB2.0 应用的 PHP 框架. Yii目前有两个主要的版本: 2.0 和 1.1.本文以YII 2.0.7为例. 环境需求 Yii2.0 框架有一些系统上的需 ...
- Yii2之控制台命令篇(console)
控制台命令 Yii 中有一个拥有丰富功能的控制台,它们主要用于创建网站后台处理的任务.在项目根目录下执行相关操作,有意思的事,可以通过 yii 自带的功能,列出当前已有的命令. 1.查看当前项目控制台 ...
随机推荐
- maven tomcat 自动部署配置
1:Tomacat 配置 /tomcat-users.xml 添加如下: <role rolename="manager-gui"/> <role rolenam ...
- C#的静态方法和实例化方法的区别
C#的静态方法和实例化方法的区别 在大多数时候,我们写一个方法,会把方法区分为实例化方法和静态方法.而当被问到静态方法和实例化方法的区别的时候,我在写这篇文章的前10分钟,或许我会回答:"静 ...
- centos mysql无法删除数据库
系统版本是CentOS Linux release 7.4.1708 (Core) 数据库版本mysql Ver 14.14 Distrib 5.6.39 在执行drop database ga-s ...
- 电脑C盘空间不足
电脑C盘空间不足,又不知道哪些文件可以删,可以下载下面的批处理文件 @echo off echo 正在清除系统垃圾文件,请稍等...... del /f /s /q %systemdrive%\*.t ...
- linux中find,locate,whereis,which关系和用法
主要有find,locate,whereis,which等 1. find是最常用也是最强大的查找命令,它可以查找任何类型的文件. find命令的一般格式为:find <指定目录>< ...
- screen小脚本
# 创建screen,执行命令,最小化screen #!/usr/bin/env bash screen_name1=$"bdapi" # 检查screen是否存在,等于0.表示s ...
- django-crontab使用
用 django-crontab 为 Django 添加定时任务 需求 做后台开发的时候,有时候会遇到这样的需求,在某个固定时间或者一定时间间隔自动触发某一事件.比如说我有一个需求要求是,周一到周五早 ...
- [LC] 114. Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 ...
- MOOC(10)- 获取响应中的cookie
- 吴裕雄--天生自然 HADOOP大数据分布式处理:安装配置JAVA
tar -xzvf jdk-8u151-linux-x64.tar.gz -C /usr/local/src sudo vim /etc/profile .编辑/etc/profile # JAVA ...