litvinab / cron-event
当前symfony2 bundle基于存储在数据库中的计时器在应用内部生成事件。
Requires
- php: >=5.5
- symfony/framework-bundle: ~2.1
- symfony/security-bundle: ~2.1
This package is not auto-updated.
Last update: 2024-09-14 18:53:15 UTC
README
用于设置和运行基于cron的定时器和事件的symfony2 bundle。它根据存储在数据库中的计时器在应用内部生成事件。
当前bundle只支持MongoDB。
安装和检查步骤
-
在项目根目录下运行命令:
composer require litvinab/cron-event
-
在
AppKernel.php
中添加new Litvinab\Bundle\CronEventBundle\CronEventBundle()
-
设置cron任务:每分钟运行一次
php app/console cron:run
-
为了测试目的,将bundle测试路由添加到
routing.yml
cron:
resource: "@CronEventBundle/Resources/config/routing.yml"
prefix: /cron
-
要添加测试计时器(1分钟计时器)和事件,请访问
http://your-domain/cron/
-
添加的调度将在此页面上显示:
http://your-domain/cron/show
,status
字段应该是未过期
-
在步骤#5后1-2分钟刷新
http://your-domain/cron/show
页面。status
字段应该是过期
,这意味着bundle运行正常。
!! 请记住从 routing.yml
中删除测试路由。将其留下是不安全的。
支持的事件类型
timer
- 应用程序中的事件将在N毫秒后触发。
event
- 应用程序中的事件将在指定的日期和时间触发。
如何使用
1. 在您的代码中设置事件
在控制器中
// get cron manager $cronManager = $this->get('cron_event.manager'); // set timer with: human name, name, period // name of the symfony event: `cron_event.` + name $timer = $cronManager->setTimer('My timer', 'test_timer', 60);
2. 添加cron事件订阅者
当然,如果您愿意,您可以创建事件监听器。
services.yml
services: app.subscriber.cron: class: AppBundle\EventSubscriber\CronSubscriber calls: - [setLogger, [@cron_event.logger]] tags: - { name: kernel.event_subscriber }
/YourBundle/EventSubscriber/CronSubscriber.php
<?php namespace AppBundle\EventSubscriber; use Litvinab\Bundle\CronEventBundle\Events\CronEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Class CronSubscriber */ class CronSubscriber implements EventSubscriberInterface { /** * @var Cron Logger */ private $logger; /** * Set cron logger * * @param $logger */ public function setLogger($logger) { $this->logger = $logger; } /** * Get subscribed events * * @return array */ public static function getSubscribedEvents() { return array( 'cron_event.test_timer' => array('onCronTestEvent', 0) ); } /** * Test event * * @param CronEvent $cronEvent */ public function onCronTestEvent(CronEvent $cronEvent) { // confirm that event is executed $this->logger->addInfo('onCronTestEvent'); // delete cron event from DB $cronEvent->delete(); } }
3. 检查日志
CronEvent bundle提供它自己的记录器。记录器的服务名称是 cron_event.logger
。
onCronTestEvent
字符串应该在2-3分钟后出现在 app/logs/cron.log
文件中。
控制台命令
cron:run
- 此命令应该在每分钟或其他时间段在 crontab
中启动;
cron:list
- 列出所有调度;