今天用yii開發的系統中要配置一個自定執行的腳本
1.配置好product/config/console.php里面需要用到的組件,像數據庫連接
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=testdrive',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
),
2.繼承CConsoleCommand寫入自己的命令類。
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, 增加一行
30 2 * * * php /path/to/console.php cleanup xxx這里的參數放action >> /path/to/logfile
需要在Yii應用目錄下創建和入口文件同級的console.php:
<?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);
上面的意思是說每天晚上兩點自動執行清理任務,簡單幾步就完成了強大的自動化功能任務,是不是夠簡單?
常見問題:
1).如果crontab 沒有自動執行,仔細檢測你的語法是否正確。
2).確定protected/yiic 文件是否有執行權限, 如果沒有使用命令 chmod +x yiic 授權