假设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. CodeForces 993B Open Communication(STL 模拟)

    https://codeforces.com/problemset/problem/993/b 这题不难,暴力就能过,主要是题意太难懂了 题意: 现在有两个人,每个人手中有一对数,第一个人手中的数是n ...

  2. British postal system to launch parcel postboxes

    1 单词 parcel n. 包裹 pilot n. 试行计划 2 句子 1400 of the new boxes will be installed at 30 locations across ...

  3. Vue项目中跨域问题解决

    后台更改header 使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建) Jquery jsonp 一.后台更改header header('Access-C ...

  4. 可用的 .net core 支持 RSA 私钥加密工具类

    首先说明 MS并不建议私钥加密,而且.net 于安全的考虑,RSACryptoServiceProvider类解密时只有同时拥有公钥和私钥才可以,原因是公钥是公开的,会被多人持有,这样的数据传输是不安 ...

  5. Ubuntu中Unable to acquire the dpkg frontend lock解决方案

    根据百度总结三种方式:第三种解决了我的问题 1. ps -e|grep apt-get 结果:6965 ? 00:00:01 apt-get 执行:sudo kill 6965 #强制解锁,会删除文件 ...

  6. com.google.zxing:core 生成二维码的简单使用

    String content = ""; int size = 240; Hashtable<EncodeHintType, String> hints = new H ...

  7. Android drawable 加载效果

    <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:ones ...

  8. 高级I/O

    1.阻塞问题的几种解决模型 1.1 非阻塞模型:类似于死循环,需要适当加休眠,防止cpu占用太高:效率较低 1.2 线程异步:效率最高的一种解决方案 1.3 I/O多路转接与复用  select(低) ...

  9. Mybatis的generator自动生成代码

    mybatis-generator有三种用法:命令行.ide插件.maven插件.本次使用maven生成 环境:IDEA,mysql8,maven (1):新建项目,本次以SpringBoot项目为例 ...

  10. Lua-文件操作

    简单模式和完全模式 简单模式(simple model)拥有一个当前输入文件和一个当前输出文件,并且提供针对这些文件相关的操作. 完全模式(complete model) 使用外部的文件句柄来实现.它 ...