Yii通过控制台命令创建定时任务_PHP教程

WBOY
发布: 2016-07-13 10:34:41
原创
988 人浏览过

假设Yii项目路径为 /home/apps/

1. 创建文件 /home/apps/protected/commands/crons.php

<?<span php

</span><span $yii</span> = '/home/apps/framework/yii.php'<span ;

</span><span require_once</span>(<span $yii</span><span );  

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

Yii</span>::createConsoleApplication(<span $configFile</span>)->run(); 
登录后复制

2. 创建需要的配置文件 /home/apps/protected/config/console.php,配置需要的组件、数据库连接,日志等信息,格式类似主配置文件main.php

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

    'name'=>'Emergency',

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

    'components'=><span array</span><span (
        </span>'log'=><span array</span><span (
            </span>'class'=>'CLogRouter',
            'routes'=><span array</span><span (
                </span><span array</span><span (
                    </span>'class'=>'CFileLogRoute',
                    'levels'=>'info, warning, error',<span 
                )</span>,<span 
            )</span>,<span 
        )</span>, 
        'db'=><span array</span><span (
            </span>'class'=>'application.extensions.PHPPDO.CPdoDbConnection',
            'pdoClass' => 'PHPPDO',
            'connectionString' => 'mysql:host=xxxx;dbname=xxx',
            'emulatePrepare' => <span true</span>,
            'username' => 'xxx',
            'password' => 'xxx',
            'charset' => 'utf8',
            'tablePrefix' => 'tbl_',<span 
        )</span>,<span 
    )</span>,  
        
    'params' => <span require</span>('params.php'),<span 
);</span>
登录后复制

3. 在 /home/apps/protected/commands/ 下新建 TestCommand 类,继承 CConsoleCommand,在TestCommand中,可以使用项目的配置信息和Yii的各种方法

<?<span php  
</span><span class</span> TestCommand  <span extends</span><span  CConsoleCommand  
{  
    </span><span public</span> <span function</span><span  run()
    {  
        </span>...<span 
    }  
}</span>
登录后复制

4. 创建定时任务

$ crontab -e
登录后复制

插入

1 * * * * /home/php/bin/php -f /home/apps/<span protected</span>/commands/crons.php Test &
登录后复制

即为每小时的第一分钟执行TestCommand类中的内容,类似的可以在/home/apps/protected/commands/下新建其他类,使用命令行执行。

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/749285.htmlTechArticle假设Yii项目路径为 /home/apps/ 1. 创建文件/home/apps/protected/commands/crons.php ? = '/home/apps/framework/yii.php' ( = ( ).'/../config/console.php' ::createConsoleAppli...
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板