今天用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().")
";
echo "Usage: ".$runner->getScriptName()." <command-name> [parameters...]
";
echo "
The following commands are available:
";
$commandNames=array_keys($commands);
sort($commandNames);
echo ' - '.implode("
- ",$commandNames);
echo "
To see individual command help, use the following:
";
echo " ".$runner->getScriptName()." help <command-name>
";
}else{
echo "No available commands.
";
echo "Please define them under the following directory:
";
echo " ".Yii::app()->getCommandPath()."
";
}
}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 授权