假设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框架通过控制台命令创建定时任务的更多相关文章

  1. Yii通过控制台命令创建定时任务

    假设Yii项目路径为 /home/apps/ 1. 创建文件 /home/apps/protected/commands/crons.php <?php $yii = '/home/apps/f ...

  2. Yii框架学习笔记(二)将html前端模板整合到框架中

    选择Yii 2.0版本框架的7个理由 http://blog.chedushi.com/archives/8988 刚接触Yii谈一下对Yii框架的看法和感受 http://bbs.csdn.net/ ...

  3. yii创建控制台命令

    创建控制台命令程序1.控制台命令继承自 yii\console\Controller控制器类2.在控制器类中,定义一个或多个动作,动作与控制台子命令相对应3.在动作方法中实现业务需求的代码 运行控制台 ...

  4. YII框架的部署 通过YII脚手架程序创建应用程序系统

    1,把YII框架里面的framework复制粘贴到nginx目录下 2,创建一个商城系统: 1)修改环境变量 制定php.exe的目录 2)C:\Users\Administrator>cd C ...

  5. Laravel 5.1 中创建自定义 Artisan 控制台命令实例教程

    1.入门 Laravel通过Artisan提供了强大的控制台命令来处理非浏览器业务逻辑.要查看Laravel中所有的Artisan命令,可以通过在项目根目录运行: php artisan list 对 ...

  6. YII 框架使用之——创建应用

    linux环境为UBUNTU14.04,YII框架的版本是1.1.17 将下载的YII解压缩,压缩后会有三个文件夹,”demos,requirements,framework”,demos 当然就是演 ...

  7. Laravel创建自定义 Artisan 控制台命令实例教程

    来源:http://laravelacademy.org/post/1374.html 1.入门 Laravel通过Artisan提供了强大的控制台命令来处理非浏览器业务逻辑.要查看Laravel中所 ...

  8. Yii 框架学习--01 框架入门

    Yii 是一个高性能的,适用于开发 WEB2.0 应用的 PHP 框架. Yii目前有两个主要的版本: 2.0 和 1.1.本文以YII 2.0.7为例. 环境需求 Yii2.0 框架有一些系统上的需 ...

  9. Yii2之控制台命令篇(console)

    控制台命令 Yii 中有一个拥有丰富功能的控制台,它们主要用于创建网站后台处理的任务.在项目根目录下执行相关操作,有意思的事,可以通过 yii 自带的功能,列出当前已有的命令. 1.查看当前项目控制台 ...

随机推荐

  1. nm命令介绍

    一.参考文章 网址1:https://linuxtools-rst.readthedocs.io/zh_CN/latest/tool/nm.html 参考2: man nm 参考3:<linux ...

  2. apt GPG error

    W: GPG error: http://extras.ubuntu.com trusty Release: The following signatures couldn't be verified ...

  3. org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'socialCode' in 'class java.lang.String'

    异常: org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.Refl ...

  4. Windows Server 2008 R2 安全加固

    0x00 简介 安全加固是企业安全中及其重要的一环,其主要内容包括账号安全.认证授权.协议安全.审计安全四项,这篇博客简单整理一下Windows Server 2008 R2的安全加固方案. 0x01 ...

  5. bzoj5104 Fib数列(BSGS+二次剩余)

    快AFO了才第一次写二次剩余的题…… 显然应该将Fn写成通项公式(具体是什么写起来不方便而且大家也都知道),设t=((1+√5)/2)n,T=√5N,然后可以得到t-(-1)t/t=√5N,两边同时乘 ...

  6. Matlab高级教程_第三篇:Matlab转码C/C++方式(混编)_第二部分

    这一部分通过一些实例来进行转码和调试的讲解: 1. 输入变量.输出变量和过程内变量的内存预分配 函数代码:函数名test function [A,B] = test( mark,num,array ) ...

  7. 24)PHP,数据库的基本知识

    (1)数据库操作的基本流程: • 建立连接(认证身份) • 客户端向服务器端发送sql命令 • 服务器端执行命令,并返回执行的结果 • 客户端接收结果(并显示) • 断开连接 (2)php中操作数据库 ...

  8. transcription-coupled repair|Germ|HK|TS|Mutation|四类变异

    生命组学-可遗传变异 GC content:碱基: GC content不同的植物对应的gene length,可看作上图的转置: 由GC content看出来碱基变异程度,可以找到对应碱基改变,所以 ...

  9. 跨域问题与SpringBoot解决方案

    什么是跨域? 定义:浏览器从一个域名的网页取请求另一个域名下的东西.通俗点说,浏览器直接从A域访问B域中的资源是不被允许的,如果想要访问,就需要进行一步操作,这操作就叫"跨域".例 ...

  10. MOOC(12) - 安装连接数据库的第三方库

    1.连接数据库需要mysql-python驱动,可以官网下载离线安装包 安装 检查是否导入成功