Giter Site home page Giter Site logo

shapecode / cron-bundle Goto Github PK

View Code? Open in Web Editor NEW
56.0 5.0 25.0 1.43 MB

This bundle provides a simple interface for registering repeated scheduled tasks within your application.

Home Page: https://shapecode.github.io/cron-bundle/

License: MIT License

PHP 100.00%
cron-jobs schedule

cron-bundle's Introduction

Shapecode - Cron Bundle

paypal

PHP Version Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads License

This bundle provides a simple interface for registering repeated scheduled tasks within your application.

Install instructions

Installing this bundle can be done through these simple steps:

Add the bundle to your project through composer:

composer require shapecode/cron-bundle

Add the bundle to your config if it flex did not do it for you:

<?php

// config/bundles.php
return [
    // ...
    Shapecode\Bundle\CronBundle\ShapecodeCronBundle::class,
    // ...
];

Update your DB schema ...

... with Doctrine schema update method ...

php bin/console doctrine:schema:update --force

Creating your own tasks

Creating your own tasks with CronBundle couldn't be easier - all you have to do is create a normal Symfony2 Command (or ContainerAwareCommand) and tag it with the CronJob annotation, as demonstrated below:

<?php

declare(strict_types=1);

namespace App\DemoBundle\Command;

use Shapecode\Bundle\CronBundle\Attribute\AsCronJob;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCronJob('*/5 * * * *')]
class DemoCommand extends Command
{
    
    public function configure() : void
    {
		// Must have a name configured
		// ...
    }
    
    public function execute(InputInterface $input, OutputInterface $output) : void
    {
		// Your code here
    }
}

The interval spec ("*/5 * * * *" in the above example) use the standard cronjob schedule format and can be modified whenever you choose. You have to escape the / in this example because it would close the annotation. You can also register your command multiple times by using the annotation more than once with different values. For your CronJob to be scanned and included in future runs, you must first run php bin/console shapecode:cron:scan - it will be scheduled to run the next time you run php app/console shapecode:cron:run

Register your new Crons:

$ php bin/console shapecode:cron:scan
$ php bin/console shapecode:cron:run

Running your cron jobs automatically

This bundle is designed around the idea that your tasks will be run with a minimum interval - the tasks will be run no more frequently than you schedule them, but they can only run when you trigger then (by running bin/console shapecode:cron:run).

To facilitate this, you can create a cron job on your system like this:

*/5 * * * * php /path/to/symfony/bin/console shapecode:cron:run

This will schedule your tasks to run at almost every 5 minutes - for instance, tasks which are scheduled to run every 3 minutes will only run every 5 minutes.

Disabling and enabling individual cron jobs from the command line

This bundle allows you to easily disable and enable individual scheduled CronJobs from the command-line.

To disable a CronJob, run: bin/console shapecode:cron:disable your:cron:job, where your:cron:job is the name of the CronJob in your project you would like to disable.

Running the above will disable your CronJob until you manually enable it again. Please note that even though the next_run field on the cron_job table will still hold a datetime value, your disabled cronjob will not be run.

To enable a cron job, run: bin/console shapecode:cron:enable your:cron:job, where your:cron:job is the name of the CronJob in your project you would like to enable.

Config

By default, all cronjobs run until they are finished (or exceed the default timeout of 60s set by the Process component. When running cronjob from a controller, a timeout for running cronjobs can be useful as the HTTP request might get killed by PHP due to a maximum execution limit. By specifying a timeout, all jobs get killed automatically, and the correct job result (which would not indicate any success) will be persisted (see #26). A default value of null lets the Process component use its default timeout, otherwise the specified timeout in seconds (as float) is applied (see Process component docs). Important: The timeout is applied to every cronjob, regardless from where (controller or CLI) it is executed.

shapecode_cron:
    timeout: null # default. A number (of type float) can be specified

cron-bundle's People

Contributors

declanv avatar frostiede avatar garvek avatar gemorroj avatar lsimeonov avatar nicklog avatar nicohaase avatar stevenjbrookes avatar zeichen32 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

Watchers

 avatar  avatar  avatar  avatar  avatar

cron-bundle's Issues

Foreign key constraint error upon deleting jobs

Me again!

If I remove a cronjob and run php bin/console shapecode:cron:scan , I get a database error

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (mydb.cron_job_result, CONSTRAINT FK_ABC123XYZ FOREIGN KEY (cron_job_id) REFERENCES cron_job (id))

Deprecation in Symfony 4.2

Deprecation reported by the Symfony Framework:

"A tree builder without a root node is deprecated since Symfony 4.2 and will not be supported anymore in 5.0"

Context:

  • \vendor\symfony\config\Definition\Builder\TreeBuilder.php:30 {...}
  • \vendor\shapecode\cron-bundle\src\DependencyInjection\Configuration.php:22 {
    --- {
    --- $treeBuilder = new TreeBuilder();
    --- $rootNode = $treeBuilder->root('shapecode_cron');
    --- }
  • }

shapecode:crone:run --no-sleep

Hello, could you please add an option like --no-sleep to command shapecode:crone:run? I'd love to run the cron very often, but I don't like the idea of having frozen app for such a long time.

Thank you very much!

Problem when running more than 60 jobs

Hi,

we have problems with running more jobs than 60.

We run cronshape each minute via system cron. In your code, there is 1s sleep in cycle in CronRunCommand, so if there is more than 60 jobs, then some are executed twice.

Shapecode\Bundle\CronBundle\Entity\CronJobResultInterface cannot be found

The current master branch is broken as the CronJobResultInterface is not present anymore:

The target-entity Shapecode\Bundle\CronBundle\Entity\CronJobResultInterface cannot be found in 'Shapecode\Bundle\CronBundle\Entity\CronJob#results'.

    /**
     * @ORM\OneToMany(
     *     targetEntity="Shapecode\Bundle\CronBundle\Entity\CronJobResultInterface",
     *     mappedBy="cronJob",
     *     cascade={"persist", "remove"},
     *     orphanRemoval=true
     * )
     *
     * @var Collection<int, CronJobResult>
     */
    private Collection $results;

Question about parallel running

Hello,

Firstly, thank you for this bundle. This certainly makes Symfony based CRON jobs for projects easier. (Knocked up a basic CMS interface to read, run, rescan, and enable/disable for added usefulness.)

We have a question about CRONs running in parallel. -- What happens if a command has a schedule for every 10 minutes, but takes longer than 10 minutes to run due to unpredicted delays?

When the 20th minute comes along to run the command for a second time, does this bundle notice that the first one is still running and knows not to spawn another instance in parallel, or would another instance be run?

I ask because certain commands could become problematic when race conditions occur due to parallel runs. I am guessing this can happen with this bundle as I've not seen enough information in the 2 entity tables that could even allow the runner to detect that a command is already running.

Is an option for how to handle parallel instances (such as that in Windows Task Scheduler shown below) within future scope, or should we do something externally to prevent parallel runs?

image

An implementation within the bundle could potentially be to create the CronJobResult entity at the start of the run instead of on completion, but leaving particular properties (such as run_time and status_code as NULL until the run has completed. That way when the runner begins to run a command it could check if an existing CronJobResult entity exists for the command but with a NULL run_time or status_code.

Doing something externally (e.g. a "run" file) might not work well if the command closes due to an error, whereas (in many cases) this bundle's runner would be able to hear when a command closes due to an error. -- With the exception of external terminations (or power cuts) of course...

Cronjob Timeout

Hello, Il have some problems with long tasks, they exceeds 60 seconds and then the "running_instances "stay at 1 so the next instances are not executed.
I see a pull request merged to add timeout override possibility but qith 4.0.5 this parameter is not available.
#34
how do i get it back ?
thanks

Reset RunningInstances to 0

Several times the RunningInstances value is not being reset upon completion of a command, even though the command has completed. This means the command will never run again unless I manually reset the value.
Is it possible to have some mechanism to either check if a command is really running or not and set the value back to 0 if not, or set a timeout period where it will set back to zero if stuck on 1 for x minutes?

Remove unused method with code issue in CronJob::getInterval.

Hi there,
I'm add custom logic around the package and working with model/repository directly, but when entity manager execute sql query(findAll, findBy etc.. ), application throw exception

Fatal error: Uncaught Exception: DateInterval::__construct(): Unknown or bad format (* * * * *)

Code for reproduce: new DateInterval('* * * * *');
Class: CronJob
Method: getInterval

Error console

symfony: 4.1
cron-bundle: dev (c9c184d)

php bin/console list --format=xml
[2018-09-10 13:35:12] console.ERROR: Error thrown while running command "list --format=xml". Message: "An option with shortcut "e" already exists." {"exception":"[object] (Symfony\\Component\\Console\\Exception\\LogicException(code: 0): An option with shortcut \"e\" already exists. at S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Input\\InputDefinition.php:238)","command":"list --format=xml","message":"An option with shortcut \"e\" already exists."} []
[2018-09-10 13:35:12] console.DEBUG: Command "list --format=xml" exited with code "1" {"command":"list --format=xml","code":1} []
####################################################################################################
#######################################  10/Sep/2018 13:35:12  #####################################
####################################################################################################
___ *** ERROR *** ==> CONSOLE ______________________________________________________________________
Error thrown while running command "list --format=xml". Message: "An option with shortcut "e"
already exists."
--> exception:
  class: Symfony\Component\Console\Exception\LogicException
  message: 'An option with shortcut "e" already exists.'
  code: 0
  file: 'S:\OSPanel\domains\amasty-saas.loc\vendor\symfony\console\Input\InputDefinition.php'
  line: 238
  trace: "#0 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Input\\InputDefinition.php(222): Symfony\\Component\\Console\\Input\\InputDefinition->addOption(Object(Symfony\\Component\\Console\\Input\\InputOption))\n#1 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Command\\Command.php(298): Symfony\\Component\\Console\\Input\\InputDefinition->addOptions(Array)\n#2 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Descriptor\\XmlDescriptor.php(59): Symfony\\Component\\Console\\Command\\Command->mergeApplicationDefinition(false)\n#3 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Descriptor\\XmlDescriptor.php(110): Symfony\\Component\\Console\\Descriptor\\XmlDescriptor->getCommandDocument(Object(Shapecode\\Bundle\\CronBundle\\Command\\CronJobEditCommand))\n#4 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Descriptor\\XmlDescriptor.php(167): Symfony\\Component\\Console\\Descriptor\\XmlDescriptor->getApplicationDocument(Object(Symfony\\Bundle\\FrameworkBundle\\Console\\Application), NULL)\n#5 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Descriptor\\Descriptor.php(55): Symfony\\Component\\Console\\Descriptor\\XmlDescriptor->describeApplication(Object(Symfony\\Bundle\\FrameworkBundle\\Console\\Application), Array)\n#6 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Helper\\DescriptorHelper.php(69): Symfony\\Component\\Console\\Descriptor\\Descriptor->describe(Object(Symfony\\Component\\Console\\Output\\ConsoleOutput), Object(Symfony\\Bundle\\FrameworkBundle\\Console\\Application), Array)\n#7 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Command\\ListCommand.php(75): Symfony\\Component\\Console\\Helper\\DescriptorHelper->describe(Object(Symfony\\Component\\Console\\Output\\ConsoleOutput), Object(Symfony\\Bundle\\FrameworkBundle\\Console\\Application), Array)\n#8 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Command\\Command.php(251): Symfony\\Component\\Console\\Command\\ListCommand->execute(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#9 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Application.php(904): Symfony\\Component\\Console\\Command\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#10 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\framework-bundle\\Console\\Application.php(92): Symfony\\Component\\Console\\Application->doRunCommand(Object(Symfony\\Component\\Console\\Command\\ListCommand), Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#11 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Application.php(262): Symfony\\Bundle\\FrameworkBundle\\Console\\Application->doRunCommand(Object(Symfony\\Component\\Console\\Command\\ListCommand), Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#12 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\framework-bundle\\Console\\Application.php(75): Symfony\\Component\\Console\\Application->doRun(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#13 S:\\OSPanel\\domains\\amasty-saas.loc\\vendor\\symfony\\console\\Application.php(145): Symfony\\Bundle\\FrameworkBundle\\Console\\Application->doRun(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#14 S:\\OSPanel\\domains\\amasty-saas.loc\\bin\\console(39): Symfony\\Component\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput))\n#15 {main}"
  previous: null
command: 'list --format=xml'
message: 'An option with shortcut "e" already exists.'
___ CONSOLE ________________________________________________________________________________________
Command "list --format=xml" exited with code "1"
--> command: 'list --format=xml'
code: 1

Running individual cron tasks?

Hello and thank you for your cron bundle,

I have a question regarding running individual cron tasks. Instead of using:

* * * * * /path/to/script shapecode:cron:run

is it possible to run individual tasks, i.e. shapecode:cron:run command:name

Thank you

Cannot install on fresh Symfony 5.2 project

Hi there,

installing this bundle on a fresh Symfony 5.2 project (v5.2.1, created with "symfony new --full" today) like described in the docs yields the following error:

❯ composer require shapecode/cron-bundle
Using version ^4.0 for shapecode/cron-bundle
./composer.json has been updated
Running composer update shapecode/cron-bundle
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - shapecode/cron-bundle[4.0.0, ..., 4.0.3] require doctrine/persistence ^1.2 -> found doctrine/persistence[1.2.0, ..., 1.4.x-dev] but the package is fixed to 2.1.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
    - Root composer.json requires shapecode/cron-bundle ^4.0 -> satisfiable by shapecode/cron-bundle[4.0.0, 4.0.1, 4.0.2, 4.0.3].

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

It seems like 5.2 requires doctrine/orm ^2.8 which made the switch to doctrine/persistence ^2:

❯ composer why-not doctrine/persistence ^1.2
doctrine/common          3.1.0   requires  doctrine/persistence (^2.0)
doctrine/orm             2.8.1   requires  doctrine/persistence (^2.0)
symfony/doctrine-bridge  v5.2.1  requires  doctrine/persistence (^2)

Could you maybe check if upgrading the project to doctrine/persistence ^2 is possible?

assert ran on own entities

EntitySubscriber::setDates does an assertion
assert($entity instanceof AbstractEntity);

My own entities does not meet the assertion and the code will crash

Symfony 6.3

Hey there,
i try to switch from Symfony 6.2 to 6.3 and get the following logs:

The "Shapecode\Bundle\CronBundle\EventListener\EntitySubscriber" class implements "Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface" that is deprecated use the {@see AsDoctrineListener} attribute instead.

Since symfony/doctrine-bridge 6.3: Registering "Shapecode\Bundle\CronBundle\EventListener\EntitySubscriber" as a Doctrine subscriber is deprecated. Register it as a listener instead, using e.g. the #[AsDoctrineListener] attribute.

User Deprecated: Since symfony/doctrine-bridge 6.3: Registering "Shapecode\Bundle\CronBundle\EventListener\EntitySubscriber" as a Doctrine subscriber is deprecated. Register it as a listener instead, using e.g. the #[AsDoctrineListener] attribute.

Any chance you can fix the deprecations?

Best regards

Use $this->getContainer()->get('doctrine') give problem when command use cron generate error if command made doctrine error

Hi,

I have a custom command who eventually can generate doctrine error that I catch.
But apparently, even if I catch the error, the Entity Manager is closed (symfony/symfony#5339), and it result that Cron Job result saved failed.

I think it's happen because you use directly 'doctrine' service instead of 'register' to get the Entity manager.

Does that problem speak to you ?

Thanks in advance

Update running_instances when job finishes

Hi,

doesn't it make more sense to update a single job when it finishes and not after all jobs have been finished?

When there is a longer running job, other jobs will not be executed after this longer running job get finished.

release with php 8 support

Сurrent stable release (4.0.5) doesn't support php 8
That would be nice release new version with php 8 support

Need support for php 7.2

Currently this bundle does not support for php 7.2. Would you please support this version. Also need to support for symfony 4.2* if possible.

maxInstances Annotation produces error

When using maxInstances in the annotation, such as @CronJob("*\/5 * * * *",maxInstances=2)
upon running php bin/console shapecode:cron:scan I get the following error:

In Annotation.php line 75:

Unknown property 'maxInstances' on annotation 'Shapecode\Bundle\CronBundle
Annotation\CronJob'.

As far as I can tell, the code in src/Annotation/CronJob.php is correct and I even get the typehint for maxInstances in PHPStorm.
As this doesn't appear in the docs, it's possible that I am doing something wrong - if so, could you advise and update the docs accordingly?
Thanks

Scan can't find new cron

Hi,
I had a problem in Symfony 5.3 with the shapecode:cron:scan command because it couldn't find any CronJob.

I got deeper and I found that the problem was here: https://github.com/shapecode/cron-bundle/blob/master/src/EventListener/AnnotationJobLoaderListener.php#L40

Because of that https://symfony.com/blog/new-in-symfony-5-3-lazy-command-description

In my command I had a description like
class MyCommand extends Command { protected static $defaultDescription = '...';

and that was the problem!

With the description, the $this->application->all() return Symfony\Component\Console\Command\LazyCommand , instead of MyCommand class.
Than the LazyCommand class is used as argument for the reflection in the next line
$reflClass = new ReflectionClass($command);

Removing the description from MyCommand worked fine.

I hope that this little explanation could help someone when updating symfony

best regards

Add support doctrine/orm 3.0

Doctrine ORM 3.0 has been relased https://github.com/doctrine/orm/releases/tag/3.0.0

  Problem 1
    - Root composer.json requires shapecode/cron-bundle dev-master -> satisfiabl
e by shapecode/cron-bundle[dev-master].
    - shapecode/cron-bundle dev-master requires doctrine/orm ^2.17 -> found doct
rine/orm[2.17.0, ..., 2.18.0] but it conflicts with your root composer.json requ
ire (^3.0).

v5 branch - Command running cron jobs terminates

My observation is that I have jobs which have running_instances > 0 and, because of this, are then skipped and never executed again. Some of my jobs take up to four minutes, this is why I added a configuration file and set the process timeout to five minutes. Still I see the following in my log (output of the shapecode process):


 [OK] cronjob started successfully and is running in background.................

Running "app:update-most-recent-interaction-with-companies"
-----------------------------------------------------------

 [OK] cronjob started successfully and is running in background.................

Running "app:document-change-feed"
----------------------------------

 [Note] cronjob will not be executed. Next run is: Wed, 24 Aug 2022 19:50:00....
        -0400...................................................................

Summary
-------

 waiting for all running jobs ...

 // Cronjobs started at Wed, 24 Aug 2022 19:20:01 -0400.........................

Execute cronjobs
================

 [Info] Found 15 jobs...........................................................

Running "app:enrich-companies"
------------------------------

 [Note] cronjob will not be executed. Next run is: Wed, 24 Aug 2022 20:14:00....
        -0400...................................................................


The line that all jobs are finished is missing:

Summary
-------

 waiting for all running jobs ...

 [OK] All jobs are finished.....................................................

What can I do? I cannot see any error messages. My cronjob command looks as follows:

*/5 * * * * /usr/bin/docker exec hcw_php su symfony -c '/usr/local/bin/php -d memory_limit=2G /var/www/html/bin/console shapecode:cron:run' >> /tmp/shapecode.log 2>&1

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.