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

Laravel Action Delay Laravel Package

syamsoul/laravel-action-delay

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require syamsoul/laravel-action-delay
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Syamsoul\ActionDelay\ActionDelayServiceProvider"
    
  2. First Use Case: Delay a job execution until a specific datetime:

    use Syamsoul\ActionDelay\Facades\ActionDelay;
    
    ActionDelay::delayNow(\App\Jobs\ProcessPayment::class, now()->addHours(2));
    
  3. Where to Look First:

    • Usage Section in the README for basic syntax.
    • config/action-delay.php for customization (e.g., default queue connection).
    • app/Console/Commands/ for extending or overriding commands.

Implementation Patterns

Core Workflows

1. Delaying Jobs

  • Basic Usage:
    ActionDelay::delayNow(\App\Jobs\SendEmail::class, now()->addMinutes(15));
    
  • With Payload:
    ActionDelay::delayNow(\App\Jobs\SendEmail::class, now()->addHours(1), [
        'user_id' => 1,
        'template' => 'welcome'
    ]);
    

2. Delaying Database Queries

  • Single Query:
    ActionDelay::delayQuery(
        'users',
        fn() => User::where('active', true)->count(),
        now()->addMinutes(5)
    );
    
  • With Callback:
    ActionDelay::delayQuery(
        'user_stats',
        fn() => User::withCount('posts')->get(),
        now()->addHours(1)
    );
    

3. Delaying PHP Code

  • Anonymous Function:
    ActionDelay::delayCode(
        'log_system_health',
        fn() => Log::info('System check passed'),
        now()->addMinutes(30)
    );
    

4. Delaying External Processes

  • Artisan Command:
    ActionDelay::delayArtisan(
        'optimize:clear',
        now()->addDays(1)
    );
    

Integration Tips

Queue Configuration

  • Override the default queue connection in config/action-delay.php:
    'queue_connection' => 'redis',
    'queue' => 'delayed',
    

Customizing Delayed Jobs

  • Extend the DelayedJob model (e.g., app/Models/CustomDelayedJob.php) to add metadata:
    use Syamsoul\ActionDelay\Models\DelayedJob as BaseDelayedJob;
    
    class CustomDelayedJob extends BaseDelayedJob {
        protected $casts = [
            'metadata' => 'array',
        ];
    }
    

Interactive CLI Usage

  • Use the delay:interactive command for prompts:
    php artisan delay:interactive
    
    • Select action type (Job/Query/Code/Artisan).
    • Enter details interactively.

Scheduling via Laravel Tasks

  • Combine with Laravel’s scheduler for periodic delayed actions:
    $schedule->command('delay:run')->dailyAt('10:00');
    

Gotchas and Tips

Pitfalls

  1. Timezone Mismatches:

    • Ensure config/app.php timezone matches your delayed actions’ expectations.
    • Explicitly use Carbon instances (e.g., now('Asia/Jakarta')) for clarity.
  2. Queue Worker Stuck:

    • If delayed jobs aren’t executing, check:
      • Queue worker is running (php artisan queue:work).
      • Queue connection is healthy (e.g., Redis/Database).
      • No exceptions in storage/logs/laravel.log.
  3. Payload Serialization:

    • Complex payloads (e.g., objects) may fail. Use arrays or json_encode():
      ActionDelay::delayNow(\App\Jobs\HandleOrder::class, now()->addHour(), [
          'order' => $order->toArray(),
      ]);
      
  4. Overlapping Delays:

    • Avoid duplicate delays for the same job/query. Use a unique identifier (e.g., job_id + delayed_at).

Debugging

  1. Inspect Delayed Jobs:

    php artisan tinker
    >>> \Syamsoul\ActionDelay\Models\DelayedJob::latest()->get();
    
  2. Log Execution:

    • Add a handle() method to your delayed job to log start/end:
      public function handle() {
          Log::info("Executing delayed job: {$this->job}");
      }
      
  3. Test Locally:

    • Use php artisan queue:work --once to manually trigger delayed jobs.

Extension Points

  1. Custom Actions:

    • Extend the ActionDelay facade by binding a new command:
      ActionDelay::extend('custom', function ($delayAt, $payload) {
          // Custom logic (e.g., HTTP request)
      });
      
  2. Event Listeners:

    • Listen for delayed.job.created or delayed.job.executed events:
      use Syamsoul\ActionDelay\Events\DelayedJobCreated;
      
      DelayedJobCreated::listen(function ($job) {
          // Send notification or update UI
      });
      
  3. Middleware for Jobs:

    • Add middleware to delayed jobs (e.g., auth, rate-limiting):
      class ProcessPayment extends Job {
          use Dispatchable, InteractsWithQueue;
      
          public function handle() {
              // Job logic
          }
      
          public function middleware() {
              return [new AuthorizeUser()];
          }
      }
      
  4. Retries:

    • Configure retries in config/action-delay.php:
      'max_retries' => 3,
      'retry_after' => 60, // seconds
      

Pro Tips

  1. Bulk Delaying:

    $users = User::where('needs_notification', true)->get();
    foreach ($users as $user) {
        ActionDelay::delayNow(\App\Jobs\NotifyUser::class, now()->addMinutes(10), ['user_id' => $user->id]);
    }
    
  2. Dynamic Delays:

    • Use a callback to compute delay time:
      ActionDelay::delayNow(\App\Jobs\SyncData::class, fn() => now()->addMinutes(rand(5, 30)));
      
  3. Environment-Specific Delays:

    • Override delays in .env:
      ACTION_DELAY_DEFAULT_MINUTES=1440 # 24 hours
      
  4. Monitoring:

    • Track delayed jobs with Laravel Nova or a custom dashboard:
      Nova::resources([
          \Syamsoul\ActionDelay\Nova\DelayedJob::class,
      ]);
      
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.
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime
canaltp/sam-ecore-application-manager-bundle
canaltp/sam-ecore-security-manager-bundle