yii CConsoleCommand定时计划任务
发布时间:2015-01-12 10:16:13 来源:51推一把
【摘要】yii CConsoleCommand定时计划任务实例讲解
yii CConsoleCommand定时计划任务
1,配置好,要执行的页面。本文为 protected/commands/crons.php
</?php
defined(YII_DEBUG) or define(YII_DEBUG,true);
// including Yii
require_once(dirname(dirname(dirname(__FILE__)))./framework/yii.php);
// well use a separate config file
$configFile=dirname(dirname(__FILE__))./config/console.php;
// creating and running console application
Yii::createConsoleApplication($configFile)->run();
/?>
2,配置好product/config/console.php里面需要用到的组件,像数据库连接,其他类包。
</?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.components.base.*,
application.components.imgthumb.*,
application.models.form.*,
等等,导入所要的类包
),
components => array (
// Main DB connection
db => array (
connectionString => mysql:host=localhost;dbname=数据库名称,
emulatePrepare => true,
username => 数据库名称,
password => 数据库密码,
charset => utf8,
tablePrefix => company_、//表前缀
),
log => array (
class => CLogRouter,
routes => array (
array (
class => CFileLogRoute,
levels => error, warning
)
)
)
)
);
3,建立继承CConsoleCommand的类,在commands目录下创建一个文件,执行任务,命名为TestCommand.php
</?php
/**
* 自动化执行 命令行模式
*/
class TestCommand extends CConsoleCommand
{
public function run($args) {
//所要执行的任务,如数据符合某条件更新,删除,修改
}
}
4,打开你的linux命令窗口,创建自动任务。至于windows系统 ,是计划任务(win系统,可以谷歌如何操作),下面只讲linux系统。
crontab -e
##然后输入
1 * * * * php /具体地址/protected/commands/crons.php Test >>/具体地址/protected/commands/test.log
##上面命令说明,每分钟执行Test任务一次,把日志保存在test.log下
(*/1 * * * * php /xxx/xxx/website/yiic Test run >> /xxx/xxx/Test.log yii样例)
(*/1 * * * * php /xxx/xxx/website/yiic crontab Test >> /xxx/xxx/Test.log yii样例)
至此,自动化任务已完成。
Linux中利用crontab创建计划任务
crontab -l 显示当前的crontab 文件
crontab -e 使用编辑器编辑当前的crontab文件
/etc/init.d/crond restart 重启配置服务
**********************************************************************
实际操作:
root身份登录到命令行
输入crontab -e
按下a键进入到编辑模式
输入 0 */1 * * * /home/work/start-service.sh
同时按下ctrl+c退出编辑模式
按下shift+: 输入wq 退出 crontab
即可保存成功
如果遇到保存不成功
=======================================
Select an editor. To change later, run select-editor.
1. /bin/ed
2. /bin/nano <---- easiest
3. /usr/bin/vim.tiny
Choose 1-3 [2]: 1
========================================
恍然明白,要先选择一个编辑器。我选择了3,再试,果然成功!
**********************************************************************