yii架構通過控制台命令建立定時任務樣本_php執行個體

來源:互聯網
上載者:User

假設Yii項目路徑為 /home/apps/

1. 建立檔案 /home/apps/protected/commands/crons.php

複製代碼 代碼如下:

<?php

$yii = '/home/apps/framework/yii.php';

require_once($yii); 

$configFile = dirname(__FILE__).'/../config/console.php';

Yii::createConsoleApplication($configFile)->run();

2. 建立需要的設定檔 /home/apps/protected/config/console.php,配置需要的組件、資料庫連接,日誌等資訊,格式類似主設定檔main.php

複製代碼 代碼如下:

<?php 
return array(
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',

    'name'=>'Emergency',

    'import'=>array( 
            'application.models.*',
            'application.components.*',
            'application.extensions.*',
    ),

    'components'=>array(
        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'info, warning, error',
                ),
            ),
        ),
        'db'=>array(
            'class'=>'application.extensions.PHPPDO.CPdoDbConnection',
            'pdoClass' => 'PHPPDO',
            'connectionString' => 'mysql:host=xxxx;dbname=xxx',
            'emulatePrepare' => true,
            'username' => 'xxx',
            'password' => 'xxx',
            'charset' => 'utf8',
            'tablePrefix' => 'tbl_',
        ),
    ), 

    'params' => require('params.php'),
);

3. 在 /home/apps/protected/commands/ 下建立 TestCommand 類,繼承 CConsoleCommand,在TestCommand中,可以使用項目的配置資訊和Yii的各種方法

複製代碼 代碼如下:

<?php 
class TestCommand  extends CConsoleCommand 
{ 
    public function run()
    { 
        ...
    } 
}

4. 建立定時任務

複製代碼 代碼如下:

$ crontab -e

插入

複製代碼 代碼如下:

1 * * * * /home/php/bin/php -f /home/apps/protected/commands/crons.php Test &

即為每小時的第一分鐘執行TestCommand類中的內容,類似的可以在/home/apps/protected/commands/下建立其他類,使用命令列執行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.