Yii實(shí)現(xiàn)Command任務(wù)處理的方法詳解

字號(hào):


    本文實(shí)例講述了Yii實(shí)現(xiàn)Command任務(wù)處理的方法。分享給大家供大家參考,具體如下:
    1.配置,執(zhí)行任務(wù)所需要的組件
    任務(wù)配置文件:/protected/config/console.php
    配置方法跟配置main文件差不多
    <?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',
      // application components
      // 自動(dòng)載入的模型和組件類
      'import'=>array(
          'application.models.*',//載入"application/models/"文件夾下的所有模型類
          'application.components.*',//載入"application/components/"文件夾下的所有應(yīng)用組件類
          'application.extensions.*',//載入"application/extensions/"文件夾下的所有應(yīng)用組件類
      ),
      'components'=>array(
          // uncomment the following to use a MySQL database
          'db'=>array(
              'connectionString' => 'mysql:host=localhost;dbname=dbname',//連接mysql數(shù)據(jù)庫(kù)
              'emulatePrepare' => true,
              'username' => 'root',//MySQL數(shù)據(jù)庫(kù)用戶名
              'password' => '123456',//MySQL數(shù)據(jù)庫(kù)用戶密碼
              'charset' => 'utf8',//MySQL數(shù)據(jù)庫(kù)編碼
              'tablePrefix' => 'zd_', //MySQL數(shù)據(jù)庫(kù)表前綴
              'enableProfiling'=>true,
              'enableParamLogging'=>true,
          ),
          //加載Email組件
          'mailer' => array(
              'class'   => 'application.extensions.mailer.EMailer',
          ),
      ),
    );
    2.任務(wù)文件
    放在 /protected/commands/ 文件目錄下繼承 CConsoleCommand 基類的為任務(wù)文件 命名方法為   任務(wù)名稱+Command
    例如 GoCommand.php
    <?php
    /**
     * 自動(dòng)運(yùn)行文件
     */
    class GoCommand extends CConsoleCommand
    {
      /**
       * 死循環(huán)輸出
       */
      public function run(){
        for($i=1;$i>0;$i++){
          self::echoWord($i);
          sleep(2);//休眠2秒
          //跳出
          if(i==500){
            break;
          }
        }
      }
      /**
       * 輸出hollo word
       */
      public function echoWord($i){
        echo "hollo word --$i\n";
      }
    }
    3.執(zhí)行任務(wù)
    打開命令行工具,進(jìn)入項(xiàng)目的/protected 目錄下 輸入yiic命令即出現(xiàn)提示,提示列表顯示剛才寫的任務(wù)文件
    E:\project\app\protected>yiic
    Yii command runner (based on Yii v1.1.12)
    Usage: E:\zeee\zyd\protected\yiic.php <command-name> [parameters...]
    The following commands are available:
    - go
    - mailqueue
    - message
    - migrate
    - shell
    - webapp
    To see individual command help, use the following:
    執(zhí)行命令 yiic go 可實(shí)現(xiàn)任務(wù)處理
    希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。