Yii: 创建cronjob定时任务

十度 Yii 2016年03月24日 收藏

1. 添加环境配置

protected/config/console.php

  1. <?php
  2.  
  3. require_once('env.php');
  4.  
  5. // This is the configuration for yiic console application.
  6. // Any writable CConsoleApplication properties can be configured here.
  7. return array(
  8. 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
  9. 'name'=>'CMS Console',
  10. // application components
  11. 'components'=>array(
  12. //Main DB connection
  13. 'db'=>array(
  14. 'connectionString'=>DB_CONNECTION,
  15. 'username'=>DB_USER,
  16. 'password'=>DB_PWD,
  17. 'enableParamLogging'=>true,
  18. ),
  19. 'log'=>array(
  20. 'class'=>'CLogRouter',
  21. 'routes'=>array(
  22. array(
  23. 'class'=>'CFileLogRoute',
  24. 'levels'=>'error, warning',
  25. ),
  26. ),
  27. ),
  28. ),
  29.  
  30. );

2. 添加定时任务执行模块

protected/commands/crons.php

  1. <?php
  2. defined('YII_DEBUG') or define('YII_DEBUG',true);
  3. // including Yii
  4. require_once('/../framework/yii.php');
  5. // we'll use a separate config file
  6. $configFile='/config/console.php';
  7. // creating and running console application
  8. Yii::createConsoleApplication($configFile)->run();

3. 添加具体的定时任务

定时任务通常是一个命令行程序,从CConsoleCommand类派生,比如

protected/commands/TestCommand.php

  1. class TestCommand extends CConsoleCommand
  2. {
  3. public function run($args) {
  4. //todo
  5. }
  6. }

4. 创建cronjob

30 0 * * * www php /path/to/crons.php Test >>/path/to/logs/test.log


5. 传入参数给定时任务中的run($params)

30 0 * * * www php /path/to/crons.php Test param1 param2 ...


by iefreer