Heim > Artikel > Backend-Entwicklung > Yii通过控制台命令创建定时任务_PHP教程
假设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/下新建其他类,使用命令行执行。