Doctrine adapter for SlmQueue module

Overview

SlmQueueDoctrine

Latest Stable Version Latest Unstable Version

Created by Stefan Kleff

Requirements

Note: it's necessary require the doctrine package in composer.json file.

Installation

Run composer require slm/queue-doctrine.

If you have the laminas/laminas-component-installer package installed, it will ask you to enable the module (and SlmQueue), both in Laminas and Mezzio. Otherwise, add the module to the list:

  • in Laminas MVC, enable the module by adding SlmQueueDoctrine in your application.config.php file.
  • in Mezzio, enable the module by adding SlmQueueDoctrine\ConfigProvider::class, in your config.php file.

Note: Don't forget install SlmQueue in you config file, which is required.

Documentation

Before reading SlmQueueDoctrine documentation, please read SlmQueue documentation.

Configuring the connection

You need to register a doctrine connection which SlmQueueDoctrine will use to access the database into the service manager. Here are some examples.

Connection parameters can be defined in the application configuration:

<?php
return [
    'doctrine' => [
        'connection' => [
            // default connection name
            'orm_default' => [
                'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
                'params' => [
                    'host'     => 'localhost',
                    'port'     => '3306',
                    'user'     => 'username',
                    'password' => 'password',
                    'dbname'   => 'database',
                ]
            ]
        ]
    ],
];

Creating the table from SQL file

You must create the required table that will contain the queue's you may use the schema located in 'data/queue_default.sql'. If you change the table name look at Configuring queues

>mysql database < data/queue_default.sql

Creating the table from Doctrine Entity

There is an alternative way to create 'queue_default' table in your database by copying Doctrine Entity 'date/DefaultQueue.php' to your entity folder ('Application\Entity' in our example) and executing Doctrine's 'orm:schema-tool:update' command which should create the table for you. Notice that DefaultQueue entity is only used for table creation and is not used by this module internally.

Adding queues

return [
  'slm_queue' => [
    'queue_manager' => [
      'factories' => [
        'foo' => 'SlmQueueDoctrine\Factory\DoctrineQueueFactory'
      ]
    ]
  ]
];

Adding jobs

return [
  'slm_queue' => [
    'job_manager' => [
      'factories' => [
        'My\Job' => 'My\JobFactory'
      ]
    ]
  ]
];

Configuring queues

The following options can be set per queue ;

  • connection (defaults to 'doctrine.connection.orm_default') : Name of the registered doctrine connection service
  • table_name (defaults to 'queue_default') : Table name which should be used to store jobs
  • deleted_lifetime (defaults to 0) : How long to keep deleted (successful) jobs (in minutes)
  • buried_lifetime (defaults to 0) : How long to keep buried (failed) jobs (in minutes)
return [
  'slm_queue' => [
    'queues' => [
      'foo' => [
        // ...
      ]
    ]
  ]
];

Provided Worker Strategies

In addition to the provided strategies by SlmQueue SlmQueueDoctrine comes with these strategies;

ClearObjectManagerStrategy

This strategy will clear the ObjectManager before execution of individual jobs. The job must implement the DoctrineModule\Persistence\ObjectManagerAwareInterface or SlmQueueDoctrine\Persistence\ObjectManagerAwareInterface.

listens to:

  • process.job event at priority 1000

options:

  • none

This strategy is enabled by default.

IdleNapStrategy

When no jobs are available in the queue this strategy will make the worker wait for a specific amount time before quering the database again.

listens to:

  • process.idle event at priority 1

options:

  • nap_duration defaults to 1 (second)

This strategy is enabled by default.

Operations on queues

push

Valid options are:

  • scheduled: the time when the job will be scheduled to run next
    • numeric string or integer - interpreted as a timestamp
    • string parserable by the DateTime object
    • DateTime instance
  • delay: the delay before a job become available to be popped (defaults to 0 - no delay -)
    • numeric string or integer - interpreted as seconds
    • string parserable (ISO 8601 duration) by DateTimeInterval::__construct
    • string parserable (relative parts) by DateTimeInterval::createFromDateString
    • DateTimeInterval instance
  • priority: the lower the priority is, the sooner the job get popped from the queue (default to 1024)

Examples:

// scheduled for execution asap
$queue->push($job);

// will get executed before jobs that have higher priority
$queue->push($job, [
    'priority' => 200,
]);

// scheduled for execution 2015-01-01 00:00:00 (system timezone applies)
$queue->push($job, [
    'scheduled' => 1420070400,
]);

// scheduled for execution 2015-01-01 00:00:00 (system timezone applies)
$queue->push($job, [
    'scheduled' => '2015-01-01 00:00:00'
]);

// scheduled for execution at 2015-01-01 01:00:00
$queue->push($job, [
    'scheduled' => '2015-01-01 00:00:00',
    'delay' => 3600
]);

// scheduled for execution at now + 300 seconds
$queue->push($job, [
    'delay' => 'PT300S'
]);

// scheduled for execution at now + 2 weeks (1209600 seconds)
$queue->push($job, [
    'delay' => '2 weeks'
]);

// scheduled for execution at now + 300 seconds
$queue->push($job, [
    'delay' => new DateInterval("PT300S"))
]);

Worker actions

Interact with workers from the command line from within the public folder of your Laminas Framework 2 application

Starting a worker

Start a worker that will keep monitoring a specific queue for jobs scheduled to be processed. This worker will continue until it has reached certain criteria (exceeds a memory limit or has processed a specified number of jobs).

vendor/bin/laminas slm-queue:start <queueName>

A worker will exit when you press cntr-C after it has finished the current job it is working on. (PHP doesn't support signal handling on Windows)

Recovering jobs

To recover jobs which are in the 'running' state for prolonged period of time (specified in minutes) use the following command.

vendor/bin/laminas slm-queue:doctrine:recover <queueName> [--executionTime=]

Note : Workers that are processing a job that is being recovered are NOT stopped.

Comments
  • delete_lifetime not considered

    delete_lifetime not considered

    While executing a job, the job is removed even if the config mention 'queues' => array( array('mails' => array( 'table_name' => 'queue_default', 'delete_lifetime' => 1440, 'buried_lifetime' => 5760, 'sleep_when_idle' => 2, ) ) ),

    opened by aburcheri 30
  • Cronjob Safe Queue Processing

    Cronjob Safe Queue Processing

    I've read the following in the documentation:

    "Warning : In previous versions of SlmQueueDoctrine the worker would quit if there where no jobs available for processing. That meant you could safely create a cronjob that would start a worker every minute. If you do that now you will quickly run out of available resources."

    I'm curious as to why you would abandon this particular feature. Most/all of the queued jobs are pushed automatically, why then should someone manual run/process the queue every time? Could you perhaps add this feature back or at least explain why you abandoned it in the first place.

    By the way if I'm missing something, maybe a new way to set up Cronjobs for SlimQueueDoctrine, could you share an example. Thank you.

    opened by kenkataiwa 19
  • Remove dependency to Doctrine ORM

    Remove dependency to Doctrine ORM

    I think we don't need the dependency to Doctrine ORM Module. Doctrine Module should be enough (we mostly rely on DBAL here).

    Could somebody make the change ? @basz

    EDIT : we should completely remove the dependency to DoctrineModule at all I think, and mimic the ZfcRbac configuration.

    opened by bakura10 18
  • Worker too slow: do not empty the queue_default table

    Worker too slow: do not empty the queue_default table

    Is there a way to make the worker faster?

    For example, I add 10 actions each second but the worker execute only 5 of them per second... in this way the queue_default table increase exponentially and it will be never empty.

    How can I do?

    Thanks

    opened by pensiero 15
  • Write unit tests

    Write unit tests

    To the SlmQueueDoctrine users (ping @stefankleff, @basz) is anyone willing to write tests ? SlmQueueDoctrine is the only one not to have tests, and I'd like to have them so I can tag first version (0.2.0).

    Thanks a lot !

    opened by bakura10 14
  • Doctrine PSR container

    Doctrine PSR container

    It's still need test if Doctrine works if both dasprid/container-interop-doctrine and doctrine/doctrine-orm-module are used.

    Please, see https://github.com/juriansluiman/SlmQueueDoctrine/issues/145#issuecomment-474785002.

    opened by imonteiro 13
  • Connection issues will kill worker

    Connection issues will kill worker

    Worker should catch PDOExceptions to avoid the worker from dying.

    My 'supervised' workers are restarted three times in case of unexpected halting this however isn't enough to survive a simple mysql restart.

    The application has thrown an exception!
    PDOException
    SQLSTATE[HY000] [2002] No such file or directory
    .../vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:40
    
    opened by basz 12
  • Zend Expressive

    Zend Expressive

    Hi,

    Currently I'm migrating an Zend MVC application to Zend Expressive, which use this module.

    SlmQueue is already Expressive "ready". Anyone has used SlmQueueDoctrine with Zend Expressive? Or you are using another adapter (Sqs)?

    Thanks.

    IM

    opened by imonteiro 11
  • Unknown jobs being processed

    Unknown jobs being processed

    Hey,

    I added two queues in my configuration. The default queue worker works fine. but if I start the worker for the email queue, I get the following result. But in my database table email_queue is only one job, which does not get executed. If I remove the MaxRunsStrategy the worker processes more and more jobs, which do not exist. What is wrong?

    Console output by running php index.php queue doctrine default --start Finished worker for queue 'default':

    • 50 seconds passed
    • 22.95MB memory usage
    • 0 jobs processed
    • lifetime of 50 seconds reached

    Console output by running php index.php queue doctrine email --start Finished worker for queue 'email':

    • 30 jobs processed
    • 0 seconds passed
    • 22.75MB memory usage
    • 30 jobs processed
    • maximum of 30 jobs processed

    Configuration

    [
        'queues' => [
            'default' => [
                'table_name' => 'queue',
                'buried_lifetime' => 60 * 24 * 3,
                'deleted_lifetime' => 60
            ],
    
            'email' => [
                'table_name' => 'email_queue',
                'buried_lifetime' => 60 * 24 * 3,
                'deleted_lifetime' => 60
            ]
        ],
    
        'queue_manager' => [
            'factories' => [
                'default' => \SlmQueueDoctrine\Factory\DoctrineQueueFactory::class,
                'email' => \SlmQueueDoctrine\Factory\DoctrineQueueFactory::class,
            ]
        ],
            
        'worker_strategies' => [
            'queues' => [
                'default' => [
                    \SlmQueue\Strategy\WorkerLifetimeStrategy::class => [
                        'lifetime' => 50
                    ]
                ],
     
                'email' => [
                    \SlmQueue\Strategy\WorkerLifetimeStrategy::class => [
                        'lifetime' => 50
                    ],
    
                    \SlmQueue\Strategy\MaxRunsStrategy::class => [
                        'max_runs' => 30
                    ]
                ]
            ]
        ]
    ];
    
    opened by ghost 11
  • Doesn't work with Pgsql Database

    Doesn't work with Pgsql Database

    When adding job to queue with $queue->push($job); There is an SQL exception : SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "id" violates not-null constraint

    opened by BnitoBzh 11
  • Transfer to JouwWeb organization

    Transfer to JouwWeb organization

    We already decided to transferhttps://github.com/juriansluiman/SlmQueue to the JouwWeb organization. We also actively use SlmQueueDoctrine ourselves. I think it makes sense to also transfer this one to us.

    @basz and @juriansluiman Are you okay with this?

    opened by roelvanduijnhoven 10
  • Reload runner automatically on dev when file changes

    Reload runner automatically on dev when file changes

    While on development, it would be handy if the job queue reloads as soon as a file was changed (but only just after a job finishes obviously).

    Inspiration: https://github.com/spatie/laravel-horizon-watcher.

    enhancement 
    opened by roelvanduijnhoven 0
  • ClearObjectManagerStrategy is mostly not useful; add better strategy for clearing entity manager

    ClearObjectManagerStrategy is mostly not useful; add better strategy for clearing entity manager

    Hi there

    Fetching the ObjectManager in onClear can never be negated since ObjectManagerAwareInterface->getObjectManager() can't return null.

    This should be wrapped in a try/catch

    ClearObjectManagerStrategy

    opened by iwyg 5
  • Queue should push event when job failed, even when PHP crashed

    Queue should push event when job failed, even when PHP crashed

    There is currently no way to hook into an event that can tell you whenever a job failed reliably. When a job crashes / exits / dies during executing a requests, it will remain on status busy.

    Ideally there would be a system in place that can detect this, and that should broadcast an error event.

    Maybe this should / could be fixed on the SlmQueue level.

    enhancement 
    opened by roelvanduijnhoven 0
  • Deadlocks when fetching messages from queue

    Deadlocks when fetching messages from queue

    Once per week a cronjob creates puts approx. 2000 messages into the queue during one transaction in our system. We have 4 workers processing messages from this doctrine queue. Unfortunately, several workers usually end up in deadlocks when fetching these messags from the queue. I tried looking or solutions but did not manage to come up with anything, also did not find anything similar in the already existing issues, so I'll leave the exception information below.

    Caught exception while processing queue; An exception occurred while executing 'SELECT * FROM queue_default WHERE (status = ?) AND (queue = ?) AND (scheduled <= ?) ORDER BY priority ASC, scheduled ASC LIMIT 1 FOR UPDATE' with params [1, "my_queue", "2020-07-13 04:00:25.690387"]:
    
    SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock try restarting transaction; An exception occurred while executing 'SELECT * FROM queue_default WHERE (status = ?) AND (queue = ?) AND (scheduled <= ?) ORDER BY priority ASC, scheduled ASC LIMIT 1 FOR UPDATE' with params [1, "my_queue", "2020-07-13 04:00:25.690387"]:
    
    bug 
    opened by tadasauciunas 7
  • Expose more about job using metadata

    Expose more about job using metadata

    This PR extends the DoctrineQueue to publish scheduled and priority. Previously only id got exposed to the outside world.

    My use-case is that I would like to add a strategy that can send the time it took before the job started to an outside monitoring system.

    opened by roelvanduijnhoven 6
  • Handling memory fatal errors

    Handling memory fatal errors

    Sometimes it can happen, that script will allocate too much memory (eg. pdf generation) and then it throws uncatchable fatal error.

    SlmQueueDoctrine recovers those jobs and runs it over and over, not firing up any event, and I can't find any way to handle those errors. I can set executionTime for recover, and they will not be recovered, but those jobs are still left unprocessed in database, and they just die silently.

    What I need to do, is to not recover jobs, and set some things, eg. using Strategy. When memory is out, I can't do anything besides registering new register_shutdown_function, rising memory limit and do what I want. But this is reduntant, because I am already using Strategies to catch errors, send them to raygun or log them.

    In this case nothing seems to work, script is stopped, slmqueue is trying to recover it, and it is stopped again. No event fired.

    Is there any way to mark those jobs as finished with error, unrecoverable?

    opened by mstrychalski 3
Releases(4.2.1)
Owner
Webador
Your website, your way
Webador
An Inertia.js adapter for Statamic.

Inertia.js adapter for Statamic Statamic server side adapter for Inertia.js to build single-page apps, without building an API. Installation You can i

Adam Campbell 52 Dec 31, 2022
A Phalcon paginator adapter for Phalcon Collections

Phalcon Collection Paginator A Phalcon paginator adapter for Phalcon Collections Why create this? Being familiar with the various Pagination data adap

Angel S. Moreno 2 Oct 7, 2022
Magento 2 Module Experius Page Not Found 404. This module saves all 404 url to a database table

Magento 2 Module Experius Page Not Found 404 This module saves all 404 urls to a database table. Adds an admin grid with 404s It includes a count so y

Experius 28 Dec 9, 2022
Rector upgrades rules for Doctrine

Rector Rules for Doctrine See available Doctrine rules Install This package is already part of rector/rector package, so it works out of the box.

Rector 37 Nov 7, 2022
Support for PHP 8.1 enums in Doctrine.

Doctrine Native Enums This library provides first-class support to PHP Enums, introduced in PHP 8.1, within your Doctrine entities. Installation compo

Beno!t POLASZEK 14 Dec 15, 2022
Pageon Doctrine Data Grid Bundle

Pageon Doctrine Data Grid Bundle A bundle that wraps around the knp paginator bundle and doctrine to generate a data grid from your entity Documentati

null 1 Dec 14, 2021
Immutable value object for IPv4 and IPv6 addresses, including helper methods and Doctrine support.

IP is an immutable value object for (both version 4 and 6) IP addresses. Several helper methods are provided for ranges, broadcast and network address

Darsyn 224 Dec 28, 2022
Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer

Spot DataMapper ORM v2.0 Spot v2.x is built on the Doctrine DBAL, and targets PHP 5.4+. The aim of Spot is to be a lightweight DataMapper alternative

Spot ORM 602 Dec 27, 2022
A bundle to handle encoding and decoding of parameters using OpenSSL and Doctrine lifecycle events.

SpecShaper Encrypt Bundle A bundle to handle encoding and decoding of parameters using OpenSSL and Doctrine lifecycle events. Features include: Master

Mark Ogilvie 48 Nov 4, 2022
Doctrine extensions for PHPStan

Doctrine extensions for PHPStan PHPStan Doctrine This extension provides following features: DQL validation for parse errors, unknown entity classes a

PHPStan 478 Jan 3, 2023
This package provides a set of factories to be used with containers using the PSR-11 standard for an easy Doctrine integration in a project

psr-container-doctrine: Doctrine Factories for PSR-11 Containers Doctrine factories for PSR-11 containers. This package provides a set of factories to

Roave, LLC 84 Dec 14, 2022
Symfony Bundle to create HTML tables with bootstrap-table for Doctrine Entities.

HelloBootstrapTableBundle This Bundle provides simple bootstrap-table configuration for your Doctrine Entities. Used bootstrap-table version 1.18.3. I

Sebastian B 7 Nov 3, 2022
Dockerise Symfony Application (Symfony 6 + Clean Architecture+ DDD+ CQRS + Docker + Xdebug + PHPUnit + Doctrine ORM + JWT Auth + Static analysis)

Symfony Dockerise Symfony Application Install Docker Install Docker Compose Docker PHP & Nginx Create Symfony Application Debugging Install Xdebug Con

null 48 Jan 5, 2023
Migrations module for ProcessWire

ProcessDbMigrate Introduction This module is designed to ease the problem of migrating database changes from one PW environment to another.

Mark Evens 9 Nov 3, 2022
WHMCS Payment Gateway Module for Coinify

vrcoinify WHMCS Payment Gateway Module for Coinify Installing guide You should copy all contents from module folder to your WHMCS application folder u

VR DEV TEAM 3 Mar 15, 2022
The swiss army knife for Magento developers, sysadmins and devops. The tool provides a huge set of well tested command line commands which save hours of work time. All commands are extendable by a module API.

netz98 magerun CLI tools for Magento 2 The n98 magerun cli tools provides some handy tools to work with Magento from command line. Build Status Latest

netz98 758 Dec 28, 2022
SilverStripe Garbage Collection Module

SilverStripe Module for defining and processing Garbage Collection on SilverStripe Applications.

Brett Tasker 8 Aug 12, 2022
WHMCS Automation Module For AWS EC2 Instances.

使用方法 把AWSEC2目录直接扔到 WHMCS/modules/servers 下即可 自定义字段 cloudinit (文本框 textarea 在订单页面显示) pem (文本框 textarea 仅管理员可见) data (文本框 textarea 仅管理员可见) 特性 动态IP (关机再开

CoiaPrant 9 Jan 28, 2022
Akaunting module to use employee as a customer

Associate Employee to customer App for Akaunting to associate employee to customer. With this app contacts with the employee type can be used as custo

LibreCode coop 2 Sep 21, 2022