Giter Site home page Giter Site logo

yiisoft / yii2-queue Goto Github PK

View Code? Open in Web Editor NEW
1.1K 80.0 295.0 969 KB

Yii2 Queue Extension. Supports DB, Redis, RabbitMQ, Beanstalk and Gearman

License: BSD 3-Clause "New" or "Revised" License

PHP 95.23% Shell 1.90% Makefile 0.51% Dockerfile 2.36%
yii2 queue redis amqp gearman async beanstalk rabbitmq hacktoberfest

yii2-queue's Introduction

Yii2 Queue Extension


An extension for running tasks asynchronously via queues.

It supports queues based on DB, Redis, RabbitMQ, AMQP, Beanstalk, ActiveMQ and Gearman.

Documentation is at docs/guide/README.md.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer:

php composer.phar require --prefer-dist yiisoft/yii2-queue

Basic Usage

Each task which is sent to queue should be defined as a separate class. For example, if you need to download and save a file the class may look like the following:

class DownloadJob extends BaseObject implements \yii\queue\JobInterface
{
    public $url;
    public $file;
    
    public function execute($queue)
    {
        file_put_contents($this->file, file_get_contents($this->url));
    }
}

Here's how to send a task into the queue:

Yii::$app->queue->push(new DownloadJob([
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]));

To push a job into the queue that should run after 5 minutes:

Yii::$app->queue->delay(5 * 60)->push(new DownloadJob([
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]));

The exact way a task is executed depends on the used driver. Most drivers can be run using console commands, which the component automatically registers in your application.

This command obtains and executes tasks in a loop until the queue is empty:

yii queue/run

This command launches a daemon which infinitely queries the queue:

yii queue/listen

See the documentation for more details about driver specific console commands and their options.

The component also has the ability to track the status of a job which was pushed into queue.

// Push a job into the queue and get a message ID.
$id = Yii::$app->queue->push(new SomeJob());

// Check whether the job is waiting for execution.
Yii::$app->queue->isWaiting($id);

// Check whether a worker got the job from the queue and executes it.
Yii::$app->queue->isReserved($id);

// Check whether a worker has executed the job.
Yii::$app->queue->isDone($id);

For more details see the guide.

yii2-queue's People

Contributors

airani avatar aivchen avatar alexkart avatar arhell avatar bizley avatar brandonkelly avatar bscheshirwork avatar cebe avatar evaldemar avatar kringkaste avatar lesha701 avatar lourdas avatar luke- avatar mikehaertl avatar mkubenka avatar mtangoo avatar s1lver avatar samdark avatar sammousa avatar silverfire avatar simplefied avatar skolkin-worker avatar softark avatar tarinu avatar terraskye avatar thiagotalma avatar timkelty avatar versh23 avatar vjik avatar zhuravljov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-queue's Issues

Логирование с помощью Yii

Столкнулся с проблемой: стандартный логер Yii, видимо, не понимает, что он вызван как console-приложение, поэтому такой код:

Yii::warning('Hello', __METHOD__);

ни к чему не приводит.

MySQL server has gone away

Здравствуйте, столкнулся с проблемой если задача выполняется долго, то получаю ошибку
"Exception 'yii\db\Exception' with message 'PDOStatement::execute(): MySQL server has gone away
The SQL being executed was: UPDATE queue SET finished_at=1495695359 WHERE id='2'"
screenshot_1

Beanstalk job priority

It's possible to set a custom priority when push a job into Beanstalk server?
Do you accept a PR to implement this feature?

Job execute method

@zhuravljov Why dont you use Yii::$container->invoke([$job, 'execute']); instead of $job->execute($this);here? It will be very useful for resolving dependencies via DI container. Passing the queue object is useless IMO, we can set it to property of the job if needed. Or maybe there is another ways to simply resolve them?

После перезапуска супервизора, старые процесс остаются запущенными

После перезапуска супервизора, старые процесс остаются запущенными

В супервизоре команды запускаются через
queue/listen
При рестарте конкретной команнды
supervisorctl restart queue/listen
Рестарт производится корректно

Если перезагрузить саму службу
service supervisor restart
То все текущие процессы остаются запущенными, и также создаются новые

Такое происходит только с командами обарбатывающие queue/listen, все другие демоны перезапускаются правильно

Две запущенные команды queue/listen обарабтывают каждый job 2 раза

Max attempts to execute failed job

Hi, I would like to ask if you're not considering adding option to specify how many times job should be run if its execution fails. I would great have this feature in scenarios like sending an email when smtp server is busy or down and refuse to send it. For instance it could look like this but it would required storing new field with attempt count and Job interface change. Then each job could itself manage how many times should be rerun or just return false to not be rerun at all. Thanks a lot

Limit jobs to run and delay?

Hi, thanks for the extension.
Is it possible to add limit for the jobs to run, instead of executing all of them?
My use case: Amazon SES has a limit 14 emails per second.

Do I have to create my worker for this?

Middleware wrapper for job execution

Может стоит добавить поддержку middleware в handleMessage чтобы можно было более гибко со стороны запуск контролировать, это позволило бы внедрять и дополнительные поведения в зависимости от класса job - в том числе для организации цепочек, и логику перезапуска внедрять, или например поведение командной шины запилить - навесив middleware с локатором, который передавал бы чистый dto job в хендлер - тогда и с конструкторами #59 проблем не должно быть
Middleware регистрируются в компоненте queue, а в handleMessage по извлечении job применяются пока не вернут статус handled. если не вернут, то вызывать $job->execute();
Да и на пуш тоже можно, тогда соответственно вся логика каких-то регистраций, менеджментов, создания-несоздания идентификаторов и прочего уже выносится на конкретные midlleware которые уже могут быть driver-depended и это будет гибче чем просто события для реализации нестандартной логики

Отлов сигнала sigterm

Благодарю за такое прекрасное расширение. Хотелось бы понять как мне отлавливать sigterm.

После обновления кода воркера я перезапускаю супервизор и мне нужно, чтобы задача, которая сейчас в работе, закончила свою работу и только после этого воркер перезапустился и приступил к следующей задаче. Когда я писал руками работу с gearman я это делал через sigterm и при его отлове останавливал работу воркера. Как поступить сейчас?

Log can't be written using 'yii queue/run'

Hello !
When I use yii test/download,the Log can be written.

public function actionDownload()
{
echo 'test-download';
\Yii::error('Test,66666666');
\Yii::$app->queue->push(new DownloadService([
'url' => 'http://gglinux.com/images/dog.png',
'file' => '/vagrant/tmp/dog.png',
]));
}

But when I use yii queue/run or yii queue/listen,The error Log can't be written.And didn't show any error!

I try to figure out the reason, and I find this.
vendor/yiisoft/yii2/log/FileTarget.php:107, fopen() can't open the log file and throw an exception,But we can't get the exception.

When I change the permission of log file to 777, It work.

Command line actions missing?

Вчера еще вроде я их там видел, а сегодня после апдейта уже нет. Вобщем, моя комманд-лайн консоль не содержит команд queue/... хотя делал все как в ридми. При этом $app->queue сконфигурирован и доступен (sync). Поискал по гитхабу, скажем, "purge" и нашел акшон только в этом коммите 719e020 причем в текущем src/Command.php его уже нет. Подозреваю, что либо что-то делаю не так либо надо доки обновить?

Class zhuravljov\yii\queue\db\Queue does not exist

Приветствую. Подключаю очередь в конфиге:

'components' => [
        'queue' => [
	        'class'     => \zhuravljov\yii\queue\db\Queue::class,
	        'db'        => 'responder',
	        'tableName' => 'queue',
	        'channel'   => 'default',
	        'mutex'     => \yii\mutex\MysqlMutex::class,
        ],
    ],

При проверке в консоли получаю сообщение:

./yii queue/info
Exception 'ReflectionException' with message 'Class zhuravljov\yii\queue\db\Queue does not exist'

Execute job in a child process

Need ability to execute a job in a child process. Parent process will reseive messages from queue and run child for each job.

Задание не завершается

Драйвер db. Заполняю очередь заданиями (для теста одно задание), запускаю очередь Yii::$app->queue->run() или посредсвом консоли ./yii queue/run, задание выполняется (происходит обмен сообщениями со сторонним сервером), но само задание остается в статусе started и в БД не обновляется поле finihed_at.

Добавление (в цикле):

Yii::$app->queue->push(new Sender([
	'from'  => $send->send_from,
	'to'  => $send->send_to,
	'subject' => $send->subject,
	'message' => $send->message
]));

После выполнения:

# id, channel, job, created_at, timeout, started_at, finished_at
'13', 'queue', ?, '1493838157', '0', '1493838157', NULL

Не работает

Exception 'ReflectionException' with message 'Class zhuravljov\yii\queue\amqp\Queue does not exist'

Documentation - Examples did not work ! need help

I'm searching for live examples that might work, right now the documentation is not step forward,
since the extension is new I could not find any ways to how implement using the provided docs.
Sorry but it was hard to get without a better explanation.
Good extension, it would be crucial to me implement it.
regards,

PgsqlMutex does not support timeout.

Hi,
I'm trying to use yii2-queue with postgres db. And I've got an error:
Exception 'yii\base\InvalidParamException' with message 'PgsqlMutex does not support timeout.'

Stack trace:
#0 /project/vendor/yiisoft/yii2/mutex/Mutex.php(72): yii\mutex\PgsqlMutex->acquireLock('zhuravljov\yii\...', 3)
#1 /project/vendor/zhuravljov/yii2-queue/src/db/Driver.php(128): yii\mutex\Mutex->acquire('zhuravljov\yii\...', 3)
#2 /project/vendor/zhuravljov/yii2-queue/src/db/Driver.php(102): zhuravljov\yii\queue\db\Driver->pop()
#3 /project/vendor/zhuravljov/yii2-queue/src/db/Command.php(30): zhuravljov\yii\queue\db\Driver->run()

Not clear documentation about multiple queue usage

as i see, for usage multiple queue - we also must have multiple console controllers with id same as queue component
so special for my case

 'staffQueue' => [
            'class' => \console\components\DbQueue::class,
            'db' => 'db', // connection ID
            'tableName' => '{{%queue}}',
            'channel' => 'staffQueue', 
            'mutex' => \yii\mutex\FileMutex::class, 
        ],
        'mailQueue' => [
            'class' => \console\components\DbQueue::class,
            'db' => 'db', // connection ID
            'tableName' => '{{%queue}}',
            'channel' => 'mailQueue', 
            'mutex' => \yii\mutex\FileMutex::class, 
        ],

I need StaffQueueController and MailQueueController for listen both, I think will be good to see that in guide.
And also not clear puprpose of "channel" property, if i need declare each channel as separated components.
Most expected behavior will be use one controller class for same drivers with channel as argument

    ./yii queue/listen --channel mail

Configuration error

my configuration like this,and i add the yiisoft/yii2-redis.but yii cant't find the "\zhuravljov\yii\queue\redis\Queue",and show 500 error. I am strange with this,can you tell me how to solve

return [
'bootstrap' => ['queue'],
'components' => [
'queue' => [
'class' => \zhuravljov\yii\queue\redis\Queue::class,
'redis' => 'redis', // connection ID
'channel' => 'queue', // queue channel
],
],
];

Catch exception

    public function run() {
        try {
            throw  new \Exception("出错了");
        } catch (\Exception $exc) {
           
        }
    }

Listen will automatically exit

Ошибка при запуске консольной команды через systemd или supervisord

В мануале написано:

"Команда listen запускает обработку очереди в режиме демона. Очередь опрашивается непрерывно. Если добавляются новые задания, то они сразу же извлекаются и выполняются. delay - время ожидания в секундах перед следующим опросом очереди. Способ наиболее эфективен если запускать команду через демон-супервизор, например supervisord."

Во время запуска через systemd или supervisord
/usr/bin/php /home/admin/web/site.ru/public_shtml/console/yii queue/listen 60
на CENTOS 7 (но думаю на любой будет) ошибка:

PHP Notice 'yii\base\ErrorException' with message 'Undefined index: PWD'
php[1945]: in /home/admin/web/site.ru/public_shtml/vendor/zhuravljov/yii2-queue/src/Command.php:96

Там видим:
$cwd = $_SERVER['PWD'];

Нашел в Интернетах:

I just found out that $_SERVER['PWD'] is not available if you run from the command line via sudo.

После того, как прописал:
$cwd = "";

Все заработало.

Поэтому прошу рассмотреть вариант 96 строчку убрать и в 97 строке убрать четвертый параметр, т.к.
он необязателен: http://php.net/proc-open

Спасибо.

Десериализация данных

По-моему, здесь:

https://github.com/zhuravljov/yii2-queue/blob/master/src/Driver.php#L59

нужно так же как и в методе serialize вызывать функцию через call_user_func.

Причина:

В настройках установил 'serializer' => 'json_encode',, но после запуска демона получают исключение:

PHP Notice 'yii\base\ErrorException' with message 'unserialize(): Error at offset 0 of 24 bytes'

in /***/vendor/zhuravljov/yii2-queue/src/Driver.php:59

the Debugging error

Hello, When I use the Debugging

'bootstrap' => ['debug','log','queue'],

'modules' => [
    'debug' => [
        'class' => \yii\debug\Module::className(),
        'panels' => [
            'queue' => \zhuravljov\yii\queue\debug\Panel::className(),
        ],
    ],
],

show the error.
Unable to send log via yii\debug\LogTarget: Exception 'yii\base\UnknownMethodException' with message 'Calling unknown method: yii\console\Request::getAbsoluteUrl()'

image

Все воркеры запускаются на всех очередях RabbitMQ

Конфиг

return [
    'components' => [
        'queue_search' => [
            'class' => \zhuravljov\yii\queue\amqp\Queue::class,
            'queueName' => 'queue_search',
        ],
        'queue_tits' => [
            'class' => \zhuravljov\yii\queue\amqp\Queue::class,
            'queueName' => 'queue_tits',
        ],
    ],
];

Запускаю два слушателя в разных командах

class QueueController extends Controller
{
    public function actionSearch()
    {
        Yii::$app->queue_search->listen();
    }

    public function actionTits()
    {
        Yii::$app->queue_tits->listen();
    }
}

Отправляю сообщение

Yii::$app->queue_search->push(new Search([
        'message' => 'Hello world!',
]));

Если запустить два слушателя
http://joxi.ru/Q2K48qMCjoGwAj.jpg

Если запустить слушателя только на search, воркер tits все равно работает. А если посмотреть в раббит то задача еще в очереди, а воркером уже выполнена.
http://joxi.ru/82QMG4ztOzql2d.jpg

А это сообщение в двух командах сразу принимается и работают два разных воркера.
Пожалуйста, подсткажите в чем проблема?

Запуск через супервизор

Хотелось бы в документации увидеть как настроить демон-супервизор. Возможно это делается просто, но у меня запустить с помощью systemd не вышло. Не понятно какой тип надо выбрать forking или simple, надо знать разветвляется этот процесс внутри или нет. Пробовал и так и так, но все равно не запустилось. Было бы неплохо в документацию добавить минимальный конфиг файл для работы команды yii queue/listen.

yii queue/run returns Exception 'yii\base\InvalidParamException' with message 'Message must be zhuravljov\yii\queue\Job object.'

When I run yii queue/run
I get the Exception 'yii\base\InvalidParamException' with message 'Message must be zhuravljov\yii\queue\Job object.'
This error is triggered in the zhuravljov\yii\queue
I created the class according to your https://github.com/zhuravljov/yii2-queue/blob/master/docs/guide/usage.md.
Thanks,
Jonathan
protected function handleMessage($id, $message)
{
$job = $this->serializer->unserialize($message);
if (!($job instanceof Job)) {
throw new InvalidParamException('Message must be ' . Job::class . ' object.');
}
class DownloadJob extends \yii\base\Object implements \zhuravljov\yii\queue\Job
{

public $url;
public $file;
  // add the function below
public function execute($queue)
{
    file_put_contents($this->file, file_get_contents($this->url));
}

}

Yii::$app->queue->push(new DownloadJob([
'url' => 'http://google.ca',
'file' => 'C:\xampp\htdocs\yii2\Yii2_advanced_doing_it_easy\advanced\frontend\web\uploads\filetest.txt',
]));

There are an error at migrations

php yii migrate --migrationPath=@zhuravljov/yii/queue/db/migrations

There are two migrations, choose yes. Then...

Error:
PHP Fatal error: Class 'M161119140200Queue' not found in /home/admin/web/site.ru/public_shtml/vendor/yiisoft/yii2/console/controllers/MigrateController.php

Yii 2.0.11.2

Beanstalk bury jobs

Hi, in case of error or Exception thrown during job execution, how can I bury the job?

I've tried with EVENT_AFTER_EXEC_ERROR, like this (in my ./yii.php script):

$application->queue->on(\zhuravljov\yii\queue\Queue::EVENT_AFTER_EXEC_ERROR, function ($event) {
    $queue = $event->sender;
    $queue->getPheanstalk()->bury($event->job);
});

and

$application->queue->on(\zhuravljov\yii\queue\Queue::EVENT_AFTER_EXEC_ERROR, function ($event) {
    $queue = $event->sender;
    $queue->getPheanstalk()->bury($event->id);
});

But they both fails because Pheanstalkd want a \Pheanstalk\Job as parameter of bury method.

Also tried with

$application->queue->on(\zhuravljov\yii\queue\Queue::EVENT_AFTER_EXEC_ERROR, function ($event) {
    $queue = $event->sender;
    $job = $queue->getPheanstalk()->peek($event->id);
    $queue->getPheanstalk()->bury($job);
});

But got this error: Error: NOT_FOUND: Job 12345 is not reserved or does not exist.

However $queue->isReserved($event->id) return true.

Do you think it's possible to change the Beanstalk driver to always bury failed jobs?
Or maybe configure it to bury or trigger events?

Использование конструкции ClassName::class

Повсеместно используется конструкция ClassName::class, которая появилась в версии php 5.5.
Может стоит указать в зависимостях "php": ">=5.5.0"?
Либо прописать Object::className() для потомков класса yii\base\Object?

Redis: Задания с задержкой

Насколько я понял из описания, то редис поддерживает отложенные задания, но у меня почему-то не получается, задание идет сразу на выполнение, или это не работает с использованием yii queue/listen ? Или надо использовать по крону yii queue/run ?

Email sending problem in queue/listen mode

Hi, thanks for the great extension.
I faced with the problem of sending email when jobs running by ./yii queue/listen.
Seems like Swift_SendmailTransport lost connection after a while.
As a temporary solving I am closing connection manually before sending emails, but I think it's wrong way.
Please tell me if you met a similar problem how you solve it?

Gearman. Виснет при попытке добавить задачу

На сервере под управлением Debian 8 установил gearman-job-server из стандартного репозитория. Сейчас top показывает 6 процессов gearmand.
Через PECL установил расширение gearman.so и добавил во все конфиги php.ini.
phpinfo() показывает наличие gearman:

extension version	1.1.2
libgearman version	1.0.6
Default TCP Host	localhost
Default TCP Port	4730

Пытаюсь завести на Yii2 Advanced App.
В common/config/main.php прописал:

'bootstrap' => ['queue'],
'components' => [
    'queue' => [
        'class' => \zhuravljov\yii\queue\gearman\Queue::class,
        'as log' => \zhuravljov\yii\queue\LogBehavior::class,
        'host' => 'localhost',
        'port' => 4730,
        'channel' => 'my_queue'
    ],
],

Создал Job

namespace common\jobs;

use common\models\Project;
use yii\base\Object;

class UploadJob extends Object implements \zhuravljov\yii\queue\Job
{
    public $projectId;

    public function run()
    {
        $project = Project::findOne($this->projectId);
        $project->status = Project::STATUS_PROCESSING;
        $project->save();
        \Yii::info('here will be upload job for project ' . $project->name);
        $project->status = Project::STATUS_READY;
        $project->save();
    }
}

В action контроллера, где нужно добавлять job в очередь, прописал:

Yii::$app->queue->push(new UploadJob([
    'projectId' => $model->id,
]));

Запускаю listener (если не запускать - проблема та же):

./yii queue/listen

Командная строка ничего не отвечает и как бы висит в режиме ожидания, то есть listener запустился и ждёт, если я правильно понимаю.
Запускаю action в браузере и когда доходит до Yii::$app->queue->push сайт виснет (остальные сайты работают) и приходится рестартовать демона apache2, а listener отключать через Ctrl+C. gearmand.log чистый от слова совсем.

Повторный запуск задачи в режиме крона

Допустим, имеется задача, которую нужно запускать каждый раз по крону.
Например, скрыть в прайсе все цены, у которых период закончился этим днем.

Есть ли смысл добавить режим для выполнения типичных задач по крону?

Для выполнения задач используются консольные команды.
yii queue/run-all
Эта команда в цикле извлекает задания из очереди и выполняет их, пока очередь не опустеет, и завершает свою работу. Это способ подойдет для обработки очереди заданий через cron.

Сейчас выбираются только те, у которых ->where(['started_at' => null])
https://github.com/zhuravljov/yii2-queue/blob/master/src/db/Driver.php#L81

И повторно они не запустятся, т.к. обновляется поле
https://github.com/zhuravljov/yii2-queue/blob/master/src/db/Driver.php#L90

Queue and data durable

hi , I think you should increase the queue data persistence support switch, for example, rabbitMQ, etc.

Подвисает выполнение обработки очереди из БД при включенном xDebug

Привет.
Собственно проблема озвучена в заголовке. Под подвисанием я имею ввиду следующее:
Компонент получает первую задачу из БД (проставляется started_at).
Далее процес виснет. Текущая задача не выполняется. Следующие задачи не берутся "в обработку"

В результате тебага выяснил что "подвисание" происходит на строке https://github.com/zhuravljov/yii2-queue/blob/master/src/cli/Queue.php#L71

How to bury a job

Hi, #58 is closed but is still an issue, because failed jobs must be buried and not deleted, otherwise you cannot debug failed jobs.

For now, I have been able to bury jobs after 3 restries with:

// Queue events
$application->queue->on(\zhuravljov\yii\queue\Queue::EVENT_AFTER_EXEC_ERROR, function (\zhuravljov\yii\queue\ErrorEvent $event) {
    /** @var \zhuravljov\yii\queue\beanstalk\Queue $queue */
    $queue = $event->sender;
    Yii::error("An error occured during job process", \zhuravljov\yii\queue\Queue::class);
    $job = $queue->getPheanstalk()->peek($event->id);
    $stats = $queue->getPheanstalk()->statsJob($job);
    if ($stats['reserves'] <= 3) {
        // Retry later
        Yii::warning("Attempts: " . $stats['reserves'] . ", retry later", \zhuravljov\yii\queue\Queue::class);
        $queue->getPheanstalk()->release($job, $stats['pri'], $stats['delay'] + 5);
    } else {
        // Bury
        Yii::error("Attempts: " . $stats['reserves']. ", too many errors, bury job", \zhuravljov\yii\queue\Queue::class);
        $queue->getPheanstalk()->bury($job);
    }
});

But it's seem like an hack, can this behavior included in library with configurable options?
I mean retry and most important bury jobs.

Отдельный воркер на задачу

Возможно ли запускать воркер на определенную задачу? например мне нужно запустить воркеры только на отправку писем, потому что письма будут отправляться большими количествами и отдельный воркер для пересчета статистики, который должен работать независимо от отправки писем.

Когда я пользовался просто gearman я могу под каждую функцию запустить свой воркер. Тут я, пока что, такой возможности не нашел. Такое уже есть? Если нет, то планируется?

Спасибо!

queue jobs interaction with DB connection

Hi,
Thanks for the great work, your extension was the most easy to install and use among all I found.

I recently saw errors in my logs saying - "General error: 2006 MySQL server has gone away"
If I am running ./yii queue/listen, and most of the jobs requires to execute a select queries. If i get it right, the connection will be created only once, and jobs that come after hours will not be able to connect to database? (I am connecting remotely to mysql)
It seems to me that extending connection with logic suggested by AnatolyRugalev is one of the best options I can go?

Is this a standard situation to run select queries in queue jobs?
Should we try to write sample db/Connection component and leave a note in docs for those who will want to use db connection in queue jobs?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.