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
0 2 * * * php console.php cleanup >> /path/to/logfile &

上面的意思是说每天晚上两点自动执行清理任务,简单几步就完成了强大的自动化功能任务.是不是够简单

posted @ 2015-05-17 21:51  科学家会武术  阅读(1077)  评论(0编辑  收藏  举报