yii架構如何通過控制台命令建立定時任務

來源:互聯網
上載者:User

假設Yii項目路徑為 /home/apps/1,建立檔案 /home/apps/protected/commands/crons.php

  1. $yii = '/home/apps/framework/yii.php';
  2. require_once($yii);
  3. $configFile = dirname(__FILE__).'/../config/console.php';
  4. Yii::createConsoleApplication($configFile)->run();
複製代碼

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

  1. return array(

  2. 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
  3. 'name'=>'Emergency',
  4. 'import'=>array(
  5. 'application.models.*',
  6. 'application.components.*',
  7. 'application.extensions.*',
  8. ),
  9. 'components'=>array(
  10. 'log'=>array(
  11. 'class'=>'CLogRouter',
  12. 'routes'=>array(
  13. array(
  14. 'class'=>'CFileLogRoute',
  15. 'levels'=>'info, warning, error',
  16. ),
  17. ),
  18. ),
  19. 'db'=>array(
  20. 'class'=>'application.extensions.PHPPDO.CPdoDbConnection',
  21. 'pdoClass' => 'PHPPDO',
  22. 'connectionString' => 'mysql:host=xxxx;dbname=xxx',
  23. 'emulatePrepare' => true,
  24. 'username' => 'xxx',
  25. 'password' => 'xxx',
  26. 'charset' => 'utf8',
  27. 'tablePrefix' => 'tbl_',
  28. ),
  29. ),

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

  31. );

複製代碼

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

  1. class TestCommand extends CConsoleCommand
  2. {
  3. public function run()
  4. {
  5. ...
  6. }
  7. }
複製代碼

4,建立定時任務$ crontab -e內容為:1 * * * * /home/php/bin/php -f /home/apps/protected/commands/crons.php Test &即為每小時的第一分鐘執行TestCommand類中的內容,類似的可以在/home/apps/protected/commands/下建立其他類,使用命令列執行。

有關crontab的用法,可以參考:

  • crontab命令基礎與執行個體
  • crontab命令的一些例子
  • linux安裝crontab詳解
  • crontab學習筆記
  • 學習linux設定定時任務的crontab命令
  • crontab 命令格式與例子
  • linux定時任務設定crontab學習
  • 不錯的crontab教程
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.