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

creadev/cron-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require colourstream/cron-bundle:dev-master
    

    Add to config/bundles.php:

    ColourStream\Bundle\CronBundle\ColourStreamCronBundle::class => ['all' => true],
    
  2. Database Setup:

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

    This creates the cron_job table to store scheduled tasks.

  3. First Use Case: Register a command to run daily:

    php bin/console cron:register "app/console my:command" "0 0 * * *" "My Daily Task"
    
    • Verify in the database (cron_job table) or via:
      php bin/console cron:list
      
  4. Trigger Execution:

    php bin/console cron:run
    

    Or set up a system cron job to run cron:run periodically (e.g., every 5 minutes):

    */5 * * * * php /path/to/your/project/bin/console cron:run >> /dev/null 2>&1
    

Implementation Patterns

Core Workflows

  1. Registering Jobs:

    • CLI:
      php bin/console cron:register "app/console my:command --option=value" "0 * * * *" "Task Description"
      
    • Programmatically (e.g., in a service or controller):
      $this->get('cron.manager')->register(
          'app/console my:command',
          '0 * * * *', // Cron expression
          'Task Description',
          ['option' => 'value'] // Command arguments
      );
      
  2. Running Jobs:

    • Manual Trigger:
      php bin/console cron:run
      
    • Web Trigger (if using the web endpoint): Configure a route (e.g., /cron/run) to call:
      $this->get('cron.manager')->run();
      
      Useful for services like EasyCron or Cron-job.org.
  3. Listing/Managing Jobs:

    • List all jobs:
      php bin/console cron:list
      
    • Disable/enable a job:
      php bin/console cron:disable 1  # Disable job with ID 1
      php bin/console cron:enable 1   # Enable it again
      
    • Delete a job:
      php bin/console cron:delete 1
      
  4. Logging and Output:

    • By default, job output is logged to Symfony’s monolog system.
    • Redirect output to a file by modifying the command in register():
      $this->get('cron.manager')->register(
          'app/console my:command >> /var/log/my_task.log 2>&1',
          '0 * * * *',
          'Task with Logging'
      );
      

Integration Tips

  1. Dependency Injection: Inject the CronManager service where needed:

    use ColourStream\Bundle\CronBundle\Manager\CronManager;
    
    class MyService {
        public function __construct(private CronManager $cronManager) {}
    
        public function scheduleTask() {
            $this->cronManager->register('app/console my:command', '* * * * *', 'Scheduled via DI');
        }
    }
    
  2. Environment-Specific Jobs: Use Symfony’s %kernel.environment% to register jobs only in specific environments (e.g., prod):

    if ('prod' === $this->getParameter('kernel.environment')) {
        $this->get('cron.manager')->register('app/console my:prod-command', '0 3 * * *', 'Production-only Task');
    }
    
  3. Dynamic Cron Expressions: Generate cron expressions dynamically (e.g., based on user input or config):

    $expression = sprintf('0 %d * * *', $hour); // Run daily at a specific hour
    $this->get('cron.manager')->register('app/console my:command', $expression, 'Dynamic Hourly Task');
    
  4. Event Listeners: Listen for job execution events (if the bundle supports them) to add pre/post hooks:

    // Example (hypothetical; verify bundle docs)
    $eventDispatcher->addListener(CronEvents::JOB_START, function ($event) {
        // Log or modify job context before execution
    });
    

Gotchas and Tips

Pitfalls

  1. Database Dependency:

    • The bundle requires a database to store job definitions. If your app uses SQLite or a non-persistent DB, jobs may reset on redeploys.
    • Workaround: Use a persistent DB (MySQL/PostgreSQL) or export/import jobs via CLI:
      php bin/console cron:export > jobs.sql
      php bin/console cron:import < jobs.sql
      
  2. Cron Expression Syntax:

    • The bundle uses standard Unix cron syntax (* * * * *). Invalid expressions (e.g., 0 25 * * *) will fail silently or cause jobs to never run.
    • Tip: Validate expressions with crontab.guru or use a library like spatie/cron-expression.
  3. Command Paths:

    • Command paths must be absolute (e.g., app/console my:command) and accessible from the CLI environment where cron:run executes.
    • Gotcha: Relative paths (e.g., console my:command) will fail.
    • Fix: Use bin/console in paths:
      php bin/console cron:register "bin/console my:command" "0 * * * *" "Fixed Path"
      
  4. Output Handling:

    • By default, job output is logged via monolog. If you redirect output (e.g., >> /file.log), ensure the user running cron:run has write permissions.
    • Tip: Use absolute paths for logs and verify permissions:
      chmod 777 /var/log/my_task.log
      
  5. Symfony Version Compatibility:

    • The bundle is tested only on Symfony 2.1. While it may work on newer versions, expect quirks (e.g., autowiring, service container changes).
    • Tip: Test thoroughly in a staging environment before deploying to production.
  6. Concurrent Executions:

    • The bundle does not handle concurrent job runs by default. If two cron:run instances execute simultaneously, jobs may run multiple times.
    • Workaround: Use a lock (e.g., file-based or database) in your jobs to prevent overlapping work:
      php bin/console cron:register "bin/console my:command --lock-file=/tmp/my_task.lock" "* * * * *" "Safe Task"
      

Debugging Tips

  1. Check Job Status:

    • Verify jobs are registered:
      php bin/console cron:list
      
    • Check the cron_job table directly for missing/incorrect entries.
  2. Log Execution:

    • Enable debug mode to see detailed logs:
      php bin/console cron:run --env=dev
      
    • Add logging to your commands:
      use Psr\Log\LoggerInterface;
      
      class MyCommand extends ContainerAwareCommand {
          protected function execute(InputInterface $input, OutputInterface $output) {
              $this->get('logger')->info('Job started', ['command' => $this->getName()]);
              // ...
          }
      }
      
  3. Test Cron Expressions:

    • Use a cron validator or test locally with at (Linux/macOS):
      echo "bin/console my:command" | at -f /dev/stdin 2023-12-31 23:59
      
  4. Permissions:

    • Ensure the user running cron:run (e.g., www-data or a cron user) has:
      • Read access to command files.
      • Write access to log files/output redirects.
      • Execute permissions on scripts.

Extension Points

  1. Custom Job Storage:

    • Override the default CronJobRepository to use a custom storage backend (e.g., Redis, cache).
    • Example: Implement ColourStream\Bundle\CronBundle\Repository\CronJobRepositoryInterface.
  2. Webhook Trigger:

    • Extend the bundle to add a webhook endpoint for external triggers (e.g., via HTTP POST).
    • Steps:
      1. Create a controller to handle POST requests.
      2. Call `$cron
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky