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

Crontab Bundle Laravel Package

ecentria/crontab-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ecentria/crontab-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3-):

    Ecentria\Bundle\CrontabBundle\EcentriaCrontabBundle::class => ['all' => true],
    
  2. Basic Configuration: Create config/packages/ecentria_crontab.yaml (Symfony 4+) or app/config/config.yml (Symfony 3-):

    ecentria_crontab:
        path: '/etc/crontab'  # Default path; adjust if needed
        jobs:
            - name: 'my_job'
              command: 'php /path/to/artisan my:command'
              schedule: '*/5 * * * *'  # Every 5 minutes
    
  3. First Use Case: Run the command to generate/update crontab entries:

    php bin/console ecentria:crontab:setup
    

    Verify entries in /etc/crontab (or your configured path).


Implementation Patterns

Workflows

  1. Development Workflow:

    • Use ecentria:crontab:setup --dry-run to preview changes without modifying the crontab.
    • Test locally with a dummy crontab file (e.g., ~/.test_crontab) by setting path in config.
  2. Deployment Workflow:

    • Store crontab configurations in version control (e.g., config/packages/ecentria_crontab.yaml).
    • Use a deployment script to run ecentria:crontab:setup post-deploy:
      php bin/console ecentria:crontab:setup --force
      
    • Restrict crontab file permissions (e.g., chmod 600 /etc/crontab) for security.
  3. Dynamic Job Management:

    • Extend the bundle by creating custom commands to add/remove jobs dynamically:
      // src/Command/AddCronJobCommand.php
      namespace App\Command;
      use Symfony\Component\Console\Command\Command;
      use Ecentria\Bundle\CrontabBundle\Service\CrontabManager;
      
      class AddCronJobCommand extends Command {
          protected static $defaultName = 'app:crontab:add';
          private $crontabManager;
      
          public function __construct(CrontabManager $crontabManager) {
              $this->crontabManager = $crontabManager;
          }
      
          protected function execute(InputInterface $input, OutputInterface $output) {
              $this->crontabManager->addJob([
                  'name' => $input->getArgument('name'),
                  'command' => $input->getArgument('command'),
                  'schedule' => $input->getArgument('schedule'),
              ]);
              return Command::SUCCESS;
          }
      }
      
  4. Environment-Specific Configs:

    • Use Symfony’s environment-aware configuration (e.g., config/packages/ecentria_crontab_{env}.yaml) to define jobs per environment (dev/staging/prod).

Integration Tips

  • Logging: Log cron job executions by wrapping commands in a script (e.g., php /path/to/script.sh >> /var/log/cron.log 2>&1).
  • Artisan Commands: Schedule Artisan commands directly:
    jobs:
        - name: 'send_queued_emails'
          command: 'php artisan queue:work --daemon --sleep=3 --tries=1'
          schedule: '* * * * *'
    
  • Environment Variables: Use placeholders for dynamic paths (e.g., command: 'php {{ bin_path }} artisan my:command'), and resolve them in a custom command.
  • Backup: Backup the crontab file before running setup:
    cp /etc/crontab /etc/crontab.bak && php bin/console ecentria:crontab:setup
    

Gotchas and Tips

Pitfalls

  1. Permissions:

    • Crontab files often require root access. Ensure the web server user (e.g., www-data) has execute permissions for scheduled commands.
    • Fix: Use sudo in commands or adjust file permissions:
      command: 'sudo -u www-data php /path/to/artisan my:command'
      
  2. Path Resolution:

    • Absolute paths in command are required. Relative paths may fail in cron’s environment.
    • Fix: Use realpath() or environment variables to resolve paths dynamically.
  3. Environment Variables:

    • Cron jobs run in a minimal environment. Variables like .env are not loaded by default.
    • Fix: Source the environment file in commands:
      command: '. /path/to/.env && php /path/to/artisan my:command'
      
  4. Overwriting Existing Entries:

    • The bundle replaces the entire crontab file by default. Existing manual entries will be lost.
    • Fix: Use --append to merge changes (if supported) or manually merge configs.
  5. Time Zone Issues:

    • Cron uses the system time zone. Jobs may run at unexpected times if the server’s time zone differs from your local time.
    • Fix: Document time zone expectations or use tools like TZ=UTC in commands.
  6. Dry Runs:

    • Always test with --dry-run before applying changes to production:
      php bin/console ecentria:crontab:setup --dry-run
      

Debugging

  1. Check Output:

    • Redirect cron output to a log file for debugging:
      command: 'php /path/to/artisan my:command >> /var/log/my_job.log 2>&1'
      
  2. Verify Syntax:

    • Use crontab -l to manually check the crontab syntax after updates.
  3. Logs:

    • Enable Symfony’s monolog to log cron job triggers:
      // config/packages/monolog.yaml
      handlers:
          cron:
              type: stream
              path: '%kernel.logs_dir%/cron.log'
              level: debug
      

Extension Points

  1. Custom Matchers:

    • Extend the bundle’s regex matching logic by creating a custom CrontabMatcher service:
      // src/Service/CustomCrontabMatcher.php
      namespace App\Service;
      use Ecentria\Bundle\CrontabBundle\Matcher\CrontabMatcherInterface;
      
      class CustomCrontabMatcher implements CrontabMatcherInterface {
          public function match(string $line, array $config): bool {
              // Custom logic
          }
      }
      
    • Bind it in services.yaml:
      services:
          App\Service\CustomCrontabMatcher:
              tags: ['ecentria.crontab.matcher']
      
  2. Pre/Post Setup Hooks:

    • Use Symfony’s event dispatcher to run logic before/after crontab updates:
      // src/EventListener/CrontabSetupListener.php
      namespace App\EventListener;
      use Ecentria\Bundle\CrontabBundle\Event\CrontabSetupEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class CrontabSetupListener implements EventSubscriberInterface {
          public static function getSubscribedEvents() {
              return [
                  CrontabSetupEvent::PRE_SETUP => 'onPreSetup',
                  CrontabSetupEvent::POST_SETUP => 'onPostSetup',
              ];
          }
      
          public function onPreSetup(CrontabSetupEvent $event) {
              // Logic before setup
          }
      
          public function onPostSetup(CrontabSetupEvent $event) {
              // Logic after setup
          }
      }
      
  3. Dynamic Config Loading:

    • Load crontab configs from a database or API by implementing a custom CrontabConfigProvider:
      // src/Service/DynamicCrontabConfigProvider.php
      namespace App\Service;
      use Ecentria\Bundle\CrontabBundle\Provider\CrontabConfigProviderInterface;
      
      class DynamicCrontabConfigProvider implements CrontabConfigProviderInterface {
          public function getConfig(): array {
              return $this->fetchFromDatabase(); // Custom logic
          }
      }
      
    • Bind it in services.yaml:
      services:
          App\Service\DynamicCrontabConfigProvider:
              tags: ['ecentria.crontab.config_provider']
      

Tips

  1. Idempotency:

    • Design jobs to be idempotent (safe to run multiple times). Use database locks or flags to prevent duplicate work.
  2. Testing:

    • Test cron jobs locally using php bin/console directly before deploying to production.
  3. Documentation:

    • Document job schedules, purposes, and owners in the config file for maintainability:
      jobs:
          - name: 'backup_database'
            command: 'php artisan
      
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