habu / task-scheduler-bundle
dev-master
2017-05-16 08:11 UTC
Requires
- php: ^7.0
- symfony/framework-bundle: ^3.3.0-BETA1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.3
- phpunit/phpunit: ^6.0
This package is not auto-updated.
Last update: 2024-09-29 03:36:35 UTC
README
PHP任务调度/延迟任务执行包,适用于Symfony 3.3+和PHP 7.0+
安装
将依赖安装到您的项目中
使用Composer安装
$ composer require habuio/task-scheduler-bundle
在您的kernel中启用bundle
打开您的app/AppKernel.php
并添加它
// [...]
public function registerBundles()
{
$bundles = [
/// [...]
new Habu\TaskSchedulerBundle\TaskSchedulerBundle(),
];
/// [...]
return $bundles;
}
// [...]
使用
创建任务服务类
从实现的角度来看,该bundle旨在在编写代码的方式上完全透明。
每个任务服务看起来都像是您编写的任何其他Symfony服务,您可以在上面调用方法,就像在其他服务上调用一样。
创建一个新文件,例如AppBundle/Task/MathTask.php
<?php
namespace AppBundle\Task;
use Habu\TaskSchedulerBundle\Task;
class MathTask extends Task
{
public function add($a, $b)
{
return $a + $b;
}
}
定义Symfony服务定义
现在,让我们打开您的bundle的services.yml
以定义我们的任务的服务定义
services:
# [...]
app.tasks.math:
class: AppBundle\Task\MathTask
tags: ['task_scheduler.task']
注意task_scheduler.task
服务标签 - 这使得服务可以在我们的任务工作器内部执行
生成任务
现在,我们已经设置了一切,让我们将任务的执行延迟到后台工作器。
为什么不在控制器(Controller/DefaultController.php
)中做呢?
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$task = $this->get('app.tasks.math');
// Defer execution of the task to a background worker.
$ref = $task->add->delay(2, 2);
// Schedule a task to be executed at a specific moment in time
$task->add->schedule(new \DateTime('2018-01-01 00:00:00'), 5, 5);
// Halt execution of the application until the worker
// finishes processing the task and yields the result.
var_dump($ref->get()); exit;
}
}
如您所见,我们的任务服务在现有的服务方法之上有一个魔法方法delay
,我们调用它将执行延迟到后台工作器,以及schedule
,它允许任务在特定时间执行。
调用如delay
和schedule
这样的方法将返回一个ReferenceInterface
对象
interface ReferenceInterface
{
/**
* Wait for, and return the result of deferred executed
* task method.
*
* @return mixed
*/
public function get();
/**
* Calling this method blocks execution of application
* flow until the execution of associated deferred task
* has been completed, and a result is available.
*
* @return void
*/
public function wait();
}
根据生产实现和bundle配置,您可以使用这些对象访问后台执行的任务的结果。
运行后台工作器任务
待定