今天用yii開發的系統中要配置一個自定執行的腳本 php
1.配置好product/config/console.php裏面須要用到的組件,像數據庫鏈接 mysql
- 'db'=>array(
- 'connectionString' => 'mysql:host=localhost;dbname=testdrive',
- 'emulatePrepare' => true,
- 'username' => 'root',
- 'password' => '',
- ),
2.繼承CConsoleCommand寫入本身的命令類。 sql
Yii提供了兩種方式去執行,若是你執行單一的任務,直接在run方法裏面寫,另一種就和Controller(控制器)中的Action(動做)相似,前面增長actionXXX,在framework/console下提供了不少實例供咱們參考使用。例如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()->db->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);
- }
- }
- }
3.使用Linux命令, vi crontab -e 打開自動執行tab, 增長一行 session
- 30 2 * * * php /path/to/console.php cleanup xxx這裏的參數放action >> /path/to/logfile
須要在Yii應用目錄下建立和入口文件同級的console.php: app
- <?php
- $yiic=dirname(__FILE__).'/protected/yiic.php';
- $config=dirname(__FILE__).'/protected/config/console.php';
- @putenv('YII_CONSOLE_COMMANDS='.dirname(__FILE__).'/protected/commands');
- require_once($yiic);
上面的意思是說天天晚上兩點自動執行清理任務,簡單幾步就完成了強大的自動化功能任務,是否是夠簡單? frontend
常見問題: yii
1).若是crontab 沒有自動執行,仔細檢測你的語法是否正確。 ide
2).肯定protected/yiic 文件是否有執行權限, 若是沒有使用命令 chmod +x yiic 受權