Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cron Bundle Laravel Package

colourstream/cron-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require colourstream/cron-bundle:dev-master
    

    Register the bundle in AppKernel.php:

    new ColourStream\Bundle\CronBundle\ColourStreamCronBundle(),
    
  2. Database Schema: Run the schema update to create the required tables:

    php app/console doctrine:schema:update --force
    
  3. First Use Case: Define a command to schedule:

    php app/console generate:bundle --namespace=Acme/DemoBundle --format=yml --dir=src --no-interaction
    

    Create a command (e.g., AcmeDemoBundle/Command/DemoCommand.php):

    namespace Acme\DemoBundle\Command;
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class DemoCommand extends Command
    {
        protected function configure()
        {
            $this->setName('demo:task');
        }
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $output->writeln('Running scheduled task!');
            return 0;
        }
    }
    
  4. Register the Command: Use the bundle’s CLI to register the command with a schedule:

    php app/console cron:scan
    

    Then define the schedule in app/config/config.yml:

    colourstream_cron:
        commands:
            demo:task:
                schedule: "0 0 * * *"  # Runs daily at midnight
    
  5. Trigger Execution: Run the cron jobs manually:

    php app/console cron:run
    

Implementation Patterns

Workflows

  1. Command Registration:

    • Use cron:scan to auto-discover commands annotated with @Cron (if supported) or manually define them in config.yml.
    • Example for manual registration:
      colourstream_cron:
          commands:
              app:send_emails:
                  schedule: "*/5 * * * *"  # Every 5 minutes
                  description: "Send daily emails"
      
  2. Webhook Integration:

    • For environments without CLI access, expose the cron:run command via a web endpoint using Symfony’s Router or a controller:
      // src/Acme/DemoBundle/Controller/CronController.php
      use Symfony\Component\HttpFoundation\Response;
      use Symfony\Bundle\FrameworkBundle\Controller\Controller;
      
      class CronController extends Controller
      {
          public function runAction()
          {
              $output = $this->get('kernel')->getContainer()->get('cron.runner')->run();
              return new Response($output);
          }
      }
      
    • Register a route in routing.yml:
      cron_run:
          path:     /cron/run
          defaults: { _controller: AcmeDemoBundle:Cron:run }
      
  3. Logging and Monitoring:

    • Log cron job executions to a dedicated table (cron_job_execution) for auditing.
    • Query executions via Doctrine:
      $executions = $this->getDoctrine()->getRepository('ColourStreamCronBundle:CronJobExecution')->findBy(['command' => 'demo:task']);
      
  4. Dynamic Scheduling:

    • Override schedules programmatically by extending the CronManager service:
      // src/Acme/DemoBundle/DependencyInjection/Compiler/CronPass.php
      use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
      use Symfony\Component\DependencyInjection\ContainerBuilder;
      
      class CronPass implements CompilerPassInterface
      {
          public function process(ContainerBuilder $container)
          {
              $definition = $container->findDefinition('colourstream_cron.manager');
              $definition->addMethodCall('setCustomSchedule', ['demo:task', '*/10 * * * *']); // Override schedule
          }
      }
      
  5. Environment-Specific Configs:

    • Use %kernel.environment% in config.yml to define different schedules per environment (e.g., dev, prod):
      colourstream_cron:
          commands:
              demo:task:
                  schedule: "%cron_demo_task_schedule%"
      
    • Override parameters in app/config/parameters.yml:
      parameters:
          cron_demo_task_schedule: "*/5 * * * *"  # Dev: every 5 mins
      

Gotchas and Tips

Pitfalls

  1. Database Schema Mismatch:

    • If you modify the bundle’s entity structure (e.g., CronJob or CronJobExecution), ensure you update the schema:
      php app/console doctrine:schema:update --force
      
    • Tip: Backup your database before running schema updates.
  2. Command Not Found:

    • Ensure the command namespace is correct in config.yml (e.g., app:send_emails vs. demo:task).
    • Verify the command is autoloaded by running:
      php app/console list
      
  3. Cron Jobs Running Too Frequently:

    • The bundle enforces the minimum interval (e.g., a job scheduled for */5 * * * * won’t run more than once every 5 minutes). However, if cron:run is called manually, it may execute pending jobs immediately.
    • Fix: Use a webhook or external cron to trigger cron:run at the desired interval.
  4. Symfony 2.1 Dependency:

    • The bundle is only tested on Symfony 2.1. While it may work on 2.0, expect quirks with newer Symfony versions (e.g., 3.x/4.x).
    • Workaround: Fork the bundle and update dependencies if needed.
  5. Missing Web Cron Endpoint:

    • The README mentions a "forthcoming web endpoint" for services like EasyCron. As of now, this is not implemented.
    • Tip: Use the workaround above (exposing cron:run via a controller).
  6. Locking Mechanism:

    • The bundle lacks built-in distributed locking for shared environments (e.g., multiple servers). Jobs may run concurrently if cron:run is triggered simultaneously.
    • Solution: Implement a lock using Redis or a database record:
      // Example pseudo-lock in a custom command
      $lock = $this->get('database_connection')->fetchOne('SELECT GET_LOCK("cron_demo_task_lock", 5)');
      if (!$lock) {
          $this->getOutput()->writeln('Lock failed. Skipping.');
          return 1;
      }
      // Execute job...
      $this->get('database_connection')->exec('SELECT RELEASE_LOCK("cron_demo_task_lock")');
      

Debugging Tips

  1. Dry Run:

    • Use cron:scan --dry-run to preview registered commands without modifying the database.
  2. Log Output:

    • Redirect cron:run output to a log file for debugging:
      php app/console cron:run >> /var/log/cron.log 2>&1
      
  3. Check Last Execution:

    • Query the cron_job_execution table to verify jobs ran:
      SELECT * FROM cron_job_execution WHERE command = 'demo:task' ORDER BY executed_at DESC LIMIT 1;
      
  4. Symfony Debug Toolbar:

    • If using Symfony’s web debug toolbar, ensure it’s enabled in config_dev.yml to inspect cron-related services.

Extension Points

  1. Custom Storage:

    • Override the default Doctrine storage by implementing ColourStream\Bundle\CronBundle\Model\CronJobManagerInterface:
      // src/Acme/DemoBundle/Model/CustomCronJobManager.php
      use ColourStream\Bundle\CronBundle\Model\CronJobManagerInterface;
      
      class CustomCronJobManager implements CronJobManagerInterface
      {
          public function findAll() { /* Custom logic */ }
          public function findByCommand($command) { /* Custom logic */ }
          // ...
      }
      
    • Register the service in services.yml:
      services:
          acme.demo.cron_job_manager:
              class: Acme\DemoBundle\Model\CustomCronJobManager
              tags:
                  - { name: colourstream_cron.manager }
      
  2. Event Listeners:

    • Listen to cron job events (e.g., cron.job.before, cron.job.after) by implementing ColourStream\Bundle\CronBundle\Event\CronEvents:
      // src/Acme/DemoBundle/EventListener/CronListener.php
      use ColourStream\Bundle\CronBundle\Event\CronEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class CronListener implements EventSubscriberInterface
      {
          public static function getSub
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity