Coder Social home page Coder Social logo

symfony-bundle's Introduction

Cron

Packagist Build status Quality Coverage Packagist License

This library enables you to have only one general crontab entry that will trigger several different cronjobs that can be defined through this library. The Cron library will decide if the job needs to run or not.

Attention: make sure you set the server crontab job to a correctly chosen frequency because if there is for example a cronjob defined in code to run every minute, your general crontab job needs to run at least every minute as well to work properly.

Use Case

Say you need two cronjobs in your application. One that will write the contents of a folder to a log file, and one that will empty the folder. This library enables you to create separate scripts (for example: cron.php) where you notify the Cron library of the two cronjobs. After defining the Jobs with their specifics, they can be added to the resolver and the run command can be given.

Your server crontab could now look something like:

* * * * * /path/to/php /path/to/cron.php >/dev/null 2>&1

The code example below is matched to this use case.

Code example

<?php

require_once __DIR__ . '/vendor/autoload.php';

// Write folder content to log every five minutes.
$job1 = new \Cron\Job\ShellJob();
$job1->setCommand('ls -la /path/to/folder');
$job1->setSchedule(new \Cron\Schedule\CrontabSchedule('*/5 * * * *'));

// Remove folder contents every hour.
$job2 = new \Cron\Job\ShellJob();
$job2->setCommand('rm -rf /path/to/folder/*');
$job2->setSchedule(new \Cron\Schedule\CrontabSchedule('0 0 * * *'));

$resolver = new \Cron\Resolver\ArrayResolver();
$resolver->addJob($job1);
$resolver->addJob($job2);

$cron = new \Cron\Cron();
$cron->setExecutor(new \Cron\Executor\Executor());
$cron->setResolver($resolver);

$cron->run();

Cron currently only support triggering shell commands. This means you can trigger anything although it is highly encouraged not to call web urls. But if you really need to here are some example commands.

* * * * * /usr/bin/lynx -source http://example.com/cron.php
* * * * * /usr/bin/wget -O - -q -t 1 http://www.example.com/cron.php
* * * * * curl -s http://example.com/cron.php

Installation

Add the following to your project's composer.json:

$ composer require cron/cron
{
    "require": {
        "cron/cron": "^1.0"
    }
}

Crontab syntax

A CRON expression is a string representing the schedule for a particular command to execute. The parts of a CRON schedule are as follows:

*    *    *    *    *    *
-    -    -    -    -    -
|    |    |    |    |    |
|    |    |    |    |    + year [optional]
|    |    |    |    +----- day of week (0 - 7) (Sunday=0 or 7)
|    |    |    +---------- month (1 - 12)
|    |    +--------------- day of month (1 - 31)
|    +-------------------- hour (0 - 23)
+------------------------- min (0 - 59)

Each of the parts supports wildcards (*), ranges (2-5) and lists (2,5,6,11).

Contributing

All code contributions - including those of people having commit access - must go through a pull request and approved by a core developer before being merged. This is to ensure proper review of all the code.

Fork the project, create a feature branch, and send us a pull request.

To ensure a consistent code base, you should make sure the code follows the Coding Standards which we borrowed from Symfony. Make sure to check out php-cs-fixer as this will help you a lot.

If you would like to help, take a look at the list of issues.

Requirements

PHP 5.5.0 or above

Author and contributors

Dries De Peuter - [email protected] - http://nousefreak.be

See also the list of contributors who participated in this project.

License

Cron is licensed under the MIT license.

symfony-bundle's People

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

symfony-bundle's Issues

Format Datetime on saveReports

Hi,

I have a locale in French on my system :

[alice@wonderland ~]$ locale
LANG=fr_FR.UTF-8
LC_CTYPE="fr_FR.UTF-8"
LC_NUMERIC="fr_FR.UTF-8"
LC_TIME="fr_FR.UTF-8"
LC_COLLATE="fr_FR.UTF-8"
LC_MONETARY="fr_FR.UTF-8"
LC_MESSAGES="fr_FR.UTF-8"
LC_PAPER="fr_FR.UTF-8"
LC_NAME="fr_FR.UTF-8"
LC_ADDRESS="fr_FR.UTF-8"
LC_TELEPHONE="fr_FR.UTF-8"
LC_MEASUREMENT="fr_FR.UTF-8"
LC_IDENTIFICATION="fr_FR.UTF-8"
LC_ALL=

As a result, the floats are with commas :

French format : 1564147674,2589
US format : 1564147674.2589

On the file Symfony-Bundle/Cron/Manager.php at line 53 :
$dbReport->setRunAt(\DateTime::createFromFormat('U.u', (string) $report->getStartTime()));
The format used is the American format.

With number_format it is possible to fix this problem.
https://php.net/manual/en/function.number-format.php

Here is an example :
$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));

Thank you for doing the necessary.
Best regards.

Overrite entitys

How i can overrite entitys? I am need to table must be in another schema and have prefix

Deprecated use of ContainerAwareCommand since Symfony 4.2

In Symfony 4.2 you get the following warning:

The "Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand" class is deprecated since Symfony 4.2, use "Symfony\Component\Console\Command\Command" with dependency injection instead.

This happens because of extending ContainerAwareCommand for cron commands
Please change it to use/respect the new approach

How to override repository

Hello, i want to override the job ans report repositories but i dont know how to, i m looking on symfony Documentation but i didnt find :(. Can you tell me quickly the method please ? Thanks you and great job for this bundle ! Thanks

Prevent Running Of Duplicate Cron Jobs

Hello!
First of all, thanks you for your bundle! It's awesome!

But I have one question:
How can I disable starting the script if the previous one still works?

I used console bin/console cron:create to add new script.
And when I put in "Command:" /usr/bin/flock -w 0 /var/tmp/file.lock command, but I resived error message "The command "/usr/bin/flock" does not exist."

In console I can exec /usr/bin/flock.

which command?

Hello

I should know the command for load the fixtures.
This is my cron job with your bundle

INSERT INTO `cron_job` (`id`, `name`, `command`, `schedule`, `description`, `enabled`) VALUES
(2, 'EleveCron', 'doctrine:fixtures:load --append', '*/3 * * * *', 'load fixtures every 3 min', 1);

this is my cron report

INSERT INTO `cron_report` (`id`, `job_id`, `run_at`, `run_time`, `exit_code`, `output`) VALUES
(1, 2, '2020-05-01 12:42:45', 0.50212001800537, 1, ''),
(2, 2, '2020-05-01 20:09:00', 0.29044103622437, 1, ''),
(3, 2, '2020-05-01 20:12:00', 0.32111287117004, 1, ''),
(4, 2, '2020-05-01 20:12:18', 0.28472805023193, 1, ''),
(5, 2, '2020-05-01 20:15:00', 0.34058713912964, 1, ''),
(6, 2, '2020-05-01 20:15:00', 0.31089615821838, 1, ''),
(7, 2, '2020-05-01 20:18:00', 0.35289192199707, 1, ''),
(8, 2, '2020-05-01 20:18:00', 0.35297203063965, 1, ''),

but the fix are not loaded. I thinks this command is not good?

php bin/console doctrine:fixtures:load --append

doctrine:fixtures:load --append

another command?

thanks you

Problem install cron/cron-bundle. Symfony 5.0.1

composer require cron/cron-bundle
Using version ^2.2 for cron/cron-bundle
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Restricting packages listed in "symfony/symfony" to "5.0.*"
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for cron/cron-bundle ^2.2 -> satisfiable by cron/cron-bundle[2.2.0].
- cron/cron-bundle 2.2.0 requires symfony/framework-bundle ^3.4|^4.0 -> no matching package found.

Potential causes:

Read https://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

Commands running more often than they are supposed to, multiple output and tons of logs?

Hi Everyone, I think I am either missing something with this bundle, or doing something wrong...

I have a few jobs:

* * * * * Video Conversion Check
5 4 * * * Generate Sitemap
15 9 * * * Email Renewal Check

I started the command php bin/console cron:start in the background yesterday.

Today there are 99 logs for Generate Sitemap job, which only should have been run once. The sitemap output has the sitemap logs repeating 5 times (as if the command ran 5x before writing the log)... There are thousands of Video Conversion Check, in the log there is up to 10 logs for the same time for this job. It should be ran every minute but it looks like it is running 10 times per minute. The email renewal check should also be running once a day but has the same result as sitemap.

Run times are all negative and I'm not sure what that means. Surely my sitemap command is not taking hours to run? It takes maybe 4 seconds to run normally.

This is what the job looks in my database:
id: 1
name: generate_sitemap
command: job:daily:generateSitemap
schedule: 5 4 * * *
description: Generates an updated sitemap daily.
enabled: 1

I have also noticed increased CPU usage with the cron command running.

Cannot call cron commands from a controller

In some situations (crontab not available on hosting plan), it might be useful to call the cron:run command periodically from a controller.

Unfortunately, this is not possible at the moment. In CommandBuilder.php, the script name is deduced from the superglobal $_SERVER, which works fine when called directly from the console (where it gives bin/console) but doesn't when called from a script (where it gives the erroneous /index.php, i.e.: /usr/local/Cellar/php/7.4.10/bin/php /index.php cron:run --env=dev in my case)

    public function build($command)
    {
        return sprintf('%s %s %s --env=%s', $this->phpExecutable, $_SERVER['SCRIPT_NAME'], $command, $this->environment);
    }

In my project, I solved it by rewriting $_SERVER['SCRIPT_NAME'] to bin/console before calling the command from the controller, but it's a bit sketchy. Maybe we could implement a setter? Or maybe there's another way to do it that I overlooked?

Command does not exist!

Hi there!
I'm trying cron/cron-bundle:1.1 in my symfony 2.8 project.
When I run app/console cron:create I follow the cronstruction to input the cronjob name, command, etc.
But when I input the command the terminal pop up the alert "Command does not exist.", and no matter what command I supply, the error still there.
screen shot 2017-11-29 at 6 47 27 pm
Is any one has this problem before?

Allow to call cron:run in crontab from any path

Currently users need to enter

cd /path/to/project/root/ && php app/console cron:run  

in their crontab. It should be possible to resolve the location of app/console without needing to cd to the project root.

Command cron:run does nothing (Symfony 4)

Running php .\bin\console cron:run somename --force does nothing.

It returns time: 0.00090408325195312 in the console but doesn't register anything in table cron_report

Preserve environment when running jobs

Firstly, thanks for publishing an awesome tool for managing cron jobs!! It has really helped simplify my workflow. I've come across a situation where I'd like to be able to run the same cron jobs in both staging as well as production environments. Ideally, I'd like to be able to set up a cron job with /usr/bin/php app/console cron:run --env=staging and have it run all enabled crons with the --env=staging switch added and /usr/bin/php app/console cron:run --env=prod and have it run all enabled crons with the --env=prod switch added. If I can have the environment flag carried across to my jobs then I won't have to specify the environment on my individual cron jobs.

Problem with entities

Hi,
I tried to integrate this bundle in a project which I am working on and everything is seems to be ok except when we try to interact with database,

The error messsage is:

An exception occurred while executing 'SELECT cron_job_id_seq.nextval FROM DUAL':                                                                   
ORA-02289: sequence does not exist                                                 
In OCI8Exception.php line 23:
                                      
ORA-02289: sequence does not exist  

And for info, the sequence cron_job_id_seq exist in database.

For info, we are using Oracle database and we use different schemas:
Schema 1 which include tables and views
Schema 2 which has some privileges on some tables and views in schema 1
And our application use schema 2 to connect to the database

The problem is already identified by us but we didn't find a solution to solve it without touching the entities in the bundle,
The similar problem is explained in this link:
https://stackoverflow.com/questions/25726573/sequence-doesnt-exist-ora-02289/25726744

The solution is to replace this line in the entity file:
@ORM\GeneratedValue(strategy="AUTO")
With:

@ORM\GeneratedValue(strategy="SEQUENCE")
@ORM\SequenceGenerator(sequenceName="schema 1.cron_job_id_seq", allocationSize=1, initialValue=1)

I also include some screenshots that might help to better understand the problem.

01
02

It will be nice if you will be able to provide a solution to solve this problem,
Thank you in advance.

Run as a worker process

First of all, thank you for a fantastic library!

My question is related to running the cron scheduler as a so called "clock" process in Heroku. Heroku instances don't have crontab. In order to start cron:run every minute, you need to have a kind of worker "daemon" process which never dies. One possible example of such process is here: https://devcenter.heroku.com/articles/php-workers.

Is there any possible way of starting cron:run as a worker process? If there is none, will it be hard to add this functionality, as it will be very helpful in such services as Heroku.

Thanks!

force run didnt work whith schedule

Command example:
"id" "name" "command" "schedule" "description" "enabled"
"2" "test" "some:test:command" "5 0 * * *" "description" "1"
I run
bin/console cron:run --force test
Command didnt run
It can be fix by

diff --git a/Command/CronRunCommand.php b/Command/CronRunCommand.php
index a8f2fcd..fba6afb 100644
--- a/Command/CronRunCommand.php
+++ b/Command/CronRunCommand.php
@@ -85,7 +85,9 @@ class CronRunCommand extends ContainerAwareCommand
         if ($dbJob->getEnabled() || $force) {
             $job = new ShellJob();
             $job->setCommand(escapeshellarg($phpExecutable) . ' bin/console ' . $dbJob->getCommand(), $rootDir);
-            $job->setSchedule(new CrontabSchedule($dbJob->getSchedule()));
+            if (!$force) {
+                $job->setSchedule(new CrontabSchedule($dbJob->getSchedule()));
+            }
             $job->raw = $dbJob;
 
             $resolver->addJob($job);

Provide a command to truncate cron reports

I run some cron jobs every minute. Within a few days I had accumulated 100 MB of database logs. It would make sense if one could automatically truncate the cron report table, e.g.

bin/console cron:reports:truncate +72

(Would delete every report older than 72h).

If there is interest, I could also do a PR.

Cron job blocked by other already running cron job

I've setup this bundle with Symfony 4.4.3 and PHP 7.4.x. and recently noticed that one already running cron job will block starting of other cron job.

I also managed to reproduce it locally, on brand new fresh instance of Symfony 5.1.8.

How to reproduce:

  1. Create two commands and setup running time, so the one is running much longer than other one.

For this purpose I quickly created two Symfony commands:

CronSleeperCommand

<?php

namespace App\Command;

use DateTime;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class CronSleeperCommand extends Command
{
    protected static $defaultName = 'cron:sleeper';

    protected function configure()
    {
        $this
            ->setDescription('Test a cron')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
		$io->success('Long sleeper started at: ' . (new DateTime())->format("g:i a"));
		for ($i = 0; $i < 300; $i++) {
			sleep (1);
		}

        $io->success('Long sleeper finished at: ' . (new DateTime())->format("g:i a"));

        return Command::SUCCESS;
    }
}

CronRunnerCommand

<?php

namespace App\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class CronRunnerCommand extends Command
{
    protected static $defaultName = 'cron:runner';

    protected function configure()
    {
        $this
            ->setDescription('Test a cron')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $io->success('it works!');

        return Command::SUCCESS;
    }
}

Cron job is set up like this:

mysql> select * from cron_job;
+----+---------+--------------+--------------+-------------+---------+
| id | name    | command      | schedule     | description | enabled |
+----+---------+--------------+--------------+-------------+---------+
|  2 | sleeper | cron:sleeper | */10 * * * * | Sleeper     |       1 |
|  3 | runner  | cron:runner  | * * * * *    | Runner      |       1 |
+----+---------+--------------+--------------+-------------+---------+

And cron deamon is running with bin/console cron:start command.

Expected:
Commands should be running without affecting each others.

Actual:
When cron:sleeper is already running, it is blocking other command from starting. That can be clearly seen in cron_report table:

mysql> select job_id, run_at, run_time, exit_code from cron_report;
+--------+---------------------+-------------------+-----------+
| job_id | run_at              | run_time          | exit_code |
+--------+---------------------+-------------------+-----------+
|      3 | 2020-12-23 16:59:00 | 0.085191965103149 |         0 |
|      3 | 2020-12-23 17:00:00 | 0.091531038284302 |         0 |
|      2 | 2020-12-23 17:00:00 |   300.86965918541 |         0 |
|      3 | 2020-12-23 17:06:00 |  0.15108489990234 |         0 |
|      3 | 2020-12-23 17:07:00 | 0.088114023208618 |         0 |
|      3 | 2020-12-23 17:08:00 | 0.086259126663208 |         0 |
|      3 | 2020-12-23 17:09:00 | 0.086606025695801 |         0 |
|      3 | 2020-12-23 17:10:00 |  0.09091591835022 |         0 |
|      2 | 2020-12-23 17:10:00 |   300.92370295525 |         0 |
|      3 | 2020-12-23 17:16:00 | 0.088279008865356 |         0 |
|      3 | 2020-12-23 17:17:00 | 0.089745998382568 |         0 |
|      3 | 2020-12-23 17:18:00 |    0.087158203125 |         0 |
|      3 | 2020-12-23 17:19:00 | 0.084715127944946 |         0 |
|      3 | 2020-12-23 17:20:00 | 0.086272954940796 |         0 |
|      2 | 2020-12-23 17:20:00 |   300.88707280159 |         0 |
|      3 | 2020-12-23 17:26:00 |   0.1083710193634 |         0 |
|      3 | 2020-12-23 17:27:00 | 0.085706949234009 |         0 |
|      3 | 2020-12-23 17:28:00 |  0.11100912094116 |         0 |
|      3 | 2020-12-23 17:29:00 |  0.50010395050049 |         0 |
+--------+---------------------+-------------------+-----------+
19 rows in set (0.00 sec)

Consider timezone for runAt

I think it makes more sense to add the local timezone to the runAt property. So, it can be easier to query reports.

Cron bundle is not saving in database from controller

Hello world,

I installed this great bundle which is easy to implement. But still at the moment I have some problems, I would like to save the cron job from my service or controller. But it's not working.
Here it is my code :

class InjectionQualificationController extends AbstractController
{
/**
     *
     * @Symfony\Component\Routing\Annotation\Route("/data_export_update_to_import_fichier", name="data_export_update_to_import_fichier")
     */
    public function updateToImportFichier(Request $request, CronHelper $cronHelper){
        
        /*
         * Entity Manager for database access
         */
        $_em_injectionQualification = $this->getDoctrine()->getRepository(InjectionQualification::class);
        $_em = $this->getDoctrine()->getManager();
        
        $injectionQualification = $_em_injectionQualification->findOneBy(array(
            "idInjectionQualification" => $request->get('id_injection_qualification')
        ));
        
        $formInjectionQualificationMappingFieldData = $this->createForm(InjectionQualification_MappingFieldDataType::class, $injectionQualification);
        
        $formInjectionQualificationMappingFieldData->handleRequest($request);
        $injectionQualification = $formInjectionQualificationMappingFieldData->getData();
        
        if ($request->isMethod('POST') && $formInjectionQualificationMappingFieldData->isSubmitted() && $formInjectionQualificationMappingFieldData->isValid()) {
            
            $_options = [];
            
            $_options['command_string'] = "php app/console app:injecterQualificationImport";
            $_options['command_arguments'] = 
                $injectionQualification->getIdInjectionQualification()
                ." ".$formInjectionQualificationMappingFieldData->get('projet')->getViewData()
                ." ".$formInjectionQualificationMappingFieldData->get('secteur')->getViewData()
                ." ".$formInjectionQualificationMappingFieldData->get('conseiller')->getViewData()
                ." ".$this->getUser()->getId()
                ." ".__DIR__ . '/../../../../public/uploads/injection_qualification/' . $injectionQualification->getPath()
            ;
            
            $_currentDate = new \DateTime();
            $_options['minute_schedule'] = $_currentDate->format('i');
            $_options['repit_minute_schedule'] = NULL;
            $_options['hour_schedule'] = $_currentDate->format('H');
            $_options['repit_hour_schedule'] = NULL;
            $_options['day_of_month_schedule'] = $_currentDate->format('d');
            $_options['repit_day_of_month_schedule'] = NULL;
            $_options['month_schedule'] = $_currentDate->format('n');
            $_options['repit_month_schedule'] = NULL;
            $_options['day_of_week_schedule'] = $_currentDate->format('w');
            $_options['repit_day_of_week_schedule'] = NULL;
            $_options['year_schedule'] = $_currentDate->format('Y');
            $_options['repit_year_schedule'] = NULL;
            
            $cronHelper->setCronTabSchedule($_options);
            $cronHelper->add();
            
            
            $objExcel = IOFactory::load(__DIR__ . '/../../../../public/uploads/injection_qualification/' . $injectionQualification->getPath());
            
            $nbreOfRows = $objExcel->getActiveSheet()->getHighestRow();
            
            $injectionQualification->setNumberOfRows($nbreOfRows);
            $injectionQualification->setFichierImported(true);
            
            $_em->persist($injectionQualification);
            $_em->flush();
            
            return
                $this->redirect(
                    $this->generateUrl('data_export_homepage') . '?success_edit_injection_qualification=1&id_injection_qualification='
                    . $injectionQualification->getIdInjectionQualification()
                );
        }
        
        /*
         * Initial vars for "Monitoring Criteria"
         */
        $conseillers = $_em->getRepository('ModelPersistBundle:Conseiller')->findAll();
        $utilisateurs = $_em->getRepository('ModelPersistBundle:Utilisateur')->findAll();
        $compagnies = $_em->getRepository('ModelPersistBundle:Compagnie')->findAll();
        $secteurs = $_em->getRepository('ModelPersistBundle:Secteur')->findAll();
        $projets = $_em->getRepository('ModelPersistBundle:Projet')->findAll();
        $naturesQualifications = $_em->getRepository('ModelPersistBundle:NatureQualification')->findAll();
        $naturesQualifications_Agenda = $_em->getRepository('ModelPersistBundle:NatureQualification')->findBy(array(
            "agenda" => 1
        ));
        $naturesComptesRendus = $_em->getRepository('ModelPersistBundle:NatureCompteRendu')->findAll();
        $naturesConfirmations = $_em->getRepository('ModelPersistBundle:NatureConfirmation')->findAll();
        $naturesConfortationsClients = $_em->getRepository('ModelPersistBundle:NatureConfortationClient')->findAll();
        $naturesReclamationsClients = $_em->getRepository('ModelPersistBundle:NatureReclamationClient')->findAll();
        $agences = $_em->getRepository('ModelPersistBundle:Agence')->findAll();
        
        return $this->render('@DataExport/Default/index.html.twig', array(
            'conseillers' => $conseillers,
            'utilisateurs' => $utilisateurs,
            'compagnies' => $compagnies,
            'secteurs' => $secteurs,
            'projets' => $projets,
            'naturesQualifications' => $naturesQualifications,
            'naturesQualifications_Agenda' => $naturesQualifications_Agenda,
            'naturesComptesRendus' => $naturesComptesRendus,
            'agences' => $agences,
            
            'naturesConfirmations' => $naturesConfirmations,
            'naturesConfortationsClients' => $naturesConfortationsClients,
            'naturesReclamationsClients' => $naturesReclamationsClients,
            
            'formInjectionQualificationMappingFieldData' => $formInjectionQualificationMappingFieldData->createView(),
            'injectionQualification' => $injectionQualification,
        ));
        
    }
}

And my service class :

<?php
namespace App\Functionnal\ModelPersistBundle\Service\Cron;


use Cron\Job\ShellJob;
use Cron\Schedule\CrontabSchedule;
use Cron\Cron;
use Cron\Resolver\ArrayResolver;
use Cron\Executor\Executor;

class CronHelper
{
    private $job;

    private $cronTabSchedule;

    private $resolver;

    private $executor;

    private $cron;

    private $options;

    public function __construct()
    {
        $this->job = new ShellJob();
        $this->resolver = new ArrayResolver();
        $this->executor = new Executor();
        $this->cron = new Cron();
    }

    public function setCronTabSchedule(?array $_options)
    {
        $this->options = $_options;
        $minuteSchedule = $this->options['minute_schedule'];
        $repitMinuteSchedule = $this->options['repit_minute_schedule'];
        $hourSchedule = $this->options['hour_schedule'];
        $repitHourSchedule = $this->options['repit_hour_schedule'];
        $dayOfMonthSchedule = $this->options['day_of_month_schedule'];
        $repitDayOfMonthSchedule = $this->options['repit_day_of_month_schedule'];
        $monthSchedule = $this->options['month_schedule'];
        $repitMonthSchedule = $this->options['repit_month_schedule'];
        $dayOfWeekSchedule = $this->options['day_of_week_schedule'];
        $repitDayOfWeekSchedule = $this->options['repit_day_of_week_schedule'];
        $yearSchedule = $this->options['year_schedule'];
        $repitYearSchedule = $this->options['repit_year_schedule'];
        $stringSchedule = $minuteSchedule . $repitMinuteSchedule . " " . $hourSchedule . $repitHourSchedule . " " . $dayOfMonthSchedule . $repitDayOfMonthSchedule . " " . $monthSchedule . $repitMonthSchedule . " " . $dayOfWeekSchedule . $repitDayOfWeekSchedule . " " . $yearSchedule . $repitYearSchedule;
        $this->cronTabSchedule = new CrontabSchedule($stringSchedule);
    }

    public function add(): void
    {
        $this->job->setCommand($this->options['command_string'] . " " . $this->options['command_arguments']);
        $this->job->setSchedule($this->cronTabSchedule);
        //dd( $this->options['command_string'] . " " . $this->options['command_arguments'] );
        $this->cron->setExecutor($this->executor);
        $this->resolver->addJob($this->job);
        $this->cron->setResolver($this->resolver);
        $this->cron->run();
    }
    
}

Could you help me please.
Thanks

Unhardcode or extend string length or db collation in entities?

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

This will produce error if collation is not "utf8" (for me it is "utf8mb4_unicode_ci" in MariaDB):
[Doctrine\DBAL\Driver\PDOException (42000)] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

How can i extend default collation (i guess cron doesn't need utfmb4) or string length (needs to be 191 chars instead of 255)?

job schedule is not properly reloaded from DB on change

hi,

if you start cron with cron:start --blocking, then the records from db are not reloaded even if they changed after starting the command, because the entity manager take care of it.
it's a problem, because no other process can change schedules if the cron process already started or without restarting it.

steps to reproduce:

  • add a job with * * * * * schedule
  • start bin/console cron:start --blocking
  • wait for the first run
  • check that the job was started
  • change the schedule of the job in db to anything
  • wait for the next run
  • check if the job was "rescheduled"

As I experienced, no mather what I change, in the variables the original schedule appear.

If I add $this->registry->getEntityManager()->clear(); to Manager.php:78 to the beginning of the function listEnabledJobs it reloads well.

Can we extend repositories from ServiceEntityRepository class instead of EntityRepository class?

Can we upgrade to

class CronJobRepository extends ServiceEntityRepository
class CronReportRepository extends ServiceEntityRepository

instead of

class CronJobRepository extends EntityRepository
class CronReportRepository extends EntityRepository

ServiceEntityRepository class extends from EntityRepository class.
ManagerRegistry class is injected in the ServiceEntityRepository class constructor.
This can help in reducing code in Cron Manager where we are injecting ManagerRegistry and getting repositories.

report error ?

Hello i make 2 crons,

when execute with :

php bin/console cron:run myCronName --schedule_now

It's ok report i 've good response from my commande.

But in sys cron i only have :

`Status: 404 Not Found
Content-type: text/html; charset=UTF-8

No input file specified.
`

i catch cron log :
time: 0.0554518699646 Content-type: text/html; charset=UTF-8

Whats' wrong ?

EDIT: crontab :

          • php /home/pathMySymfonyProject/bin/console cron:run 1>> /tmp/cron.log 2>&1

Cron job will not execute with another schedule

With this 30 6 * * 1-5 schedule the cron job will not execute.
As test I set it on my current time, for example 39 13 * * 1-5 and it works.

Another example is the this schedule * * * * * works, but not */5 * * * * or */2 * * * *
Whats here the problem?

Simplify usage of different entity manager

I wished to use a separate database for cron usage, but the bundle currently use the default entity manager with something like:

  • $this->registry->getRepository('CronCronBundle:CronJob')
  • $em = $this->registry->getManager();
  • ...

I ended to:

  • override cron.manager.class with my own (cron.manager.class: 'AppBundle\My\Cron\Manager' in parameters.yml) extending your Cron\CronBundle\Cron\Manager class.
  • override all methods that refers to default entity manager (getJobRepo(), saveJob(), saveReports(), deleteJob()).
    getJobRepo() is handy:
    I just replaced
    return $this->registry->getRepository('CronCronBundle:CronJob');
    by
    return $this->registry->getRepository('CronCronBundle:CronJob', 'my_cron_em');
    ...but other ones need to be completely rewritten.

Am I missing a better solution ?

Cron:run uses missing Doctrine class

When trying to execute:
`
$ php /var/www/bin/console cron:run

In Manager.php line 31:

Argument 1 passed to Cron\CronBundle\Cron\Manager::__construct() must be an instance of Doctrine\Persistence\ManagerRegistry, instance of D
octrine\Bundle\DoctrineBundle\Registry given, called in /var/www/var/cache/dev/ContainerLtkPqt8/getCron_ManagerService.php on line 11

cron:run [--force] [--schedule_now] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] []
`

Compatibility with "doctrine/doctrine-bundle": "~1.2"?

This bundle requires "doctrine/doctrine-bundle": "~1.3".

The current latest symfony/symfony-standard release uses version ~1.2 of the doctrine bundle. No current standard symfony releases use version ~1.3 of the doctrine bundle (as far as I can tell).

I'd like to use this package in my Symfony-based project but don't want to up the version of the doctrine bundle used beyond what is required by the standard symfony releases as there could be issues that I would have to deal with if I happen to notice them before releasing changes to production.

Does this package specifically depend on features in version ~1.3 of the doctrine bundle that aren't available in version ~1.2?

If not, would you be in a position to lower the dependency versions down a bit to make this package more easily usable with standard symfony releases?

How can i set the name of command on cron:create

Hello, good morning.

I know this is a dummy question, but let's go.
In the documentation you say that to create a new cron we can execute the commando cron:create.
When i execute this commando this message shows:

he unique name how the job will be referenced.
Name: [error] Error thrown while running command "cron:create". Message: "Please set a name."


In CronCreateCommand.php line 102:
                      
  Please set a name.  
                      

cron:create [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command>

How can i set the name of the cron?

job run time in report table is not correct

every job on a single run has almost the same running time which is not true

steps to reproduce:

  • create two jobs with a schedule of * * * * *
  • the first job should finish in seconds or less
  • the second job should finish in more than 30 seconds (sleep 30)
  • check the report

both job will show a run time of ~30sec, while the first was much quicker.

Too many arguments, expected arguments "command".

Hi,

When i try to create new cron with cron:create i get an exception.

[Symfony\Component\Console\Exception\RuntimeException] โ”‚
Too many arguments, expected arguments "command".

Can you include some example of how this bundle works, like creating a new Cron.

Thanks

Memory Limit

We run our Cron command with php -d memory_limit=4096M, but the subprocess run with the default memory_limit of the server. Is there any possibility to change the memory_limit for subprocesses ?

The symfony Process supports the following: --define memory_limit=4096

Could not open input file: bin/console

Upgrading v2.2 to v2.3 causes Could not open input file: bin/console error in cron_report.
Symfony 4.4.4

Changing the service cron.resolver argument %kernel.project_dir% to %kernel.root_dir% fixes the issue.
This was changed to %kernel.project_dir% in commit 2ad1a7c

This issue is happening because ShellJob setCommand $cwd is being set to ./src which is causing Process to try to run bin/console from the src directory

Could you add a check for Symfony 5 and adjust this argument as needed please.

Consider timezone for runAt

I think it makes more sense to add the local timezone to the runAt property. So, it can be easier to query reports.

Crontab schedule syntax validation errors

There is currently no information whether the crontab schedule syntax is valid or not.

As of now, if the validation doesn't pass, jobs are simply not added to the array of jobs that are about to be executed. This seems alright but we should, at some point, get a feedback about the schedule syntax errors or if the job's schedule did pass the validation or not.

Add OSS motivation

Explain the motivation for creating a library reusable by any PHP framework

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.