1. 程式人生 > >Yii 利用CConsoleCommand 實現計劃任務

Yii 利用CConsoleCommand 實現計劃任務

1、/protected/commands 下新建檔案crons.php
<?php
defined('YII_DEBUG') or define('YII_DEBUG',true);

// including Yii
require_once('../../framework/yii.php');//注意檔案目錄

// we'll use a separate config file
//$configFile='/config/console.php';
$configFile=dirname(dirname(__FILE__)).'/config/console.php';
// creating and running console application
?>

2、/protected/config下新建配置檔案console.php, 配置類似main.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=127.0.0.1;dbname=test',
                        'emulatePrepare' => true,
                        'username' => 'root',
                        'password' => 'root',
                        'charset' => 'utf8'                     
                ),
                'log' => array (
                        'class' => 'CLogRouter',
                        'routes' => array (
                                array (
                                        'class' => 'CFileLogRoute',
                                        'levels' => 'error, warning'
                                ) 
                        ) 
                ) 
        ) 
);

3、/protected/commands 下新建檔案TestCommand.php,注意檔案命名XyzCommand

<?php
/**
 * 自動化執行 命令列模式
 */
class TestCommand extends CConsoleCommand
{
    public function run($args)
    {
      $data = array('username' => 'ezreal', 'password' => date("Y-m-d H:i:s"));
        try {
            return Yii::app()->db->createCommand()->insert('gzc_user', $data);
        } catch (Exception $ex) {
            return null;
        }
    }

    public function test()
    {
        echo 'this is a test';
    }

}

4、linux 編輯crontab
*/2 * * * * php /var/www/html/trunk/gzcloud/protected/commands/crons.php test #插入資料操作
*/2 * * * * php /var/www/html/trunk/gzcloud/protected/commands/crons.php test test >> /home/log #在檔案log中插入字串


5、注意事項

①yiic 要給執行許可權

②/home/log 要給寫的許可權

③第一個計劃任務如果有錯誤 加上 >> /home/log  把錯誤資訊寫到log檔案裡,然後在log檔案裡查詢