三步使用cronjobs自动化去执行Yii 控制台任务

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#4) »

这篇文章将介绍使用Linux cronjobs去自动化执行Yii Console Application(控制台)任务,像每天晚上执行缓存清理,临时文件清理,发送邮件,网站备份等等,重复的工作都交给服务器后台去完成,Yii本身已经提供了强大的支持,我们所做的工作就很少,当使用yiic webapp 自动生成工程结构时,强大的Yii已经全部帮我们生成好,仅仅只需三步。

1.配置好product/config/console.php里面需要用到的组件,像数据库连接

'db'=>array(
                            'connectionString' => 'mysql:host=localhost;dbname=testdrive',
                            'emulatePrepare' => true,
                            'username' => 'root',
                            'password' => '',
                            'charset' => 'utf8',
                    ), 
  1. 继承CConsoleCommand写入自己的命令类,Yii提供了两种方式去执行,如果你执行单一的任务,直接在run方法里面写,另外一种就是同写你的Controller(控制器),前面增加actionXXX,framework/console 下面提供了很多实例供我们参考使用。

注意:避免一些名称造成莫名其妙的问题, 请遵守Yii官言文档控制台命名规则,详细查看Yii Console Application文档

CHelpCommand使用直接使用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]';
            }
    } 

使用Action执行清理命令

class CleanupCommand extends CConsoleCommand {
             
             private $sessionTableName = 'it_common_session';
             
             /**
              * 自动执行清理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);
                    }
             }
    } 
  1. 使用Linux命令, vi crontab -e 打开自动执行tab, 增加一行
30    2    * * *    /usr/local/webserver/php/bin/php php /data/console.php clean >>/path/to/logfile 

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

常见问题: 1.如果crontab 没有自动执行,仔细检测你的语法是否正确。 2.确定protected/yiic 文件是否有执行权限, 如果没有使用命令 chmod +x yiic 授权

原文出自: IT快讯网 地址: 三步使用cronjobs自动化去执行Yii 控制台任务

0 4
2 followers
Viewed: 27 874 times
Version: Unknown (update)
Category: Tutorials
Written by: Darwin Wen
Last updated by: Darwin Wen
Created on: Aug 16, 2011
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles