Support the ongoing development of Laravel.io →
posted 4 months ago
Laravel
Last updated by @najeeb-anwari 4 months ago.
0

The issue seems to be with the scheduling and handling of jobs within Laravel's queue system. The problem might be due to the simultaneous execution of the jobs causing conflicts or the command being executed too frequently.

Here are a few steps to diagnose and potentially solve the issue:

  1. Check for Job Overlap: Make sure that the jobs are not overlapping and causing conflicts. Given that your schedule is set to run every second, it might be causing overlapping jobs. Consider changing the frequency to every minute or at an interval that allows enough time for each job to complete.

  2. Use Unique Job Identifiers: Ensure that each job instance is uniquely identified and processed separately. Laravel's queue system should handle this, but it's worth double-checking.

  3. Review Job Dispatching: When dispatching the jobs, ensure that each job is dispatched with its own unique data. The current issue might be due to shared state or improper job data handling.

  4. Log Job Details: Add more detailed logging to ensure that each job is dispatched and processed with the correct data.

Here’s an improved version of your command and job with added logging and adjusted scheduling:

Command Code

<?php

namespace App\Console\Commands;

use App\Jobs\SendScheduledMessageJob;
use App\Models\ScheduledMessage;
use Illuminate\Console\Command;

class SendScheduledMessages extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:send-scheduled-messages';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send scheduled messages';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $messages = ScheduledMessage::where('scheduled_at', '<=', now())
            ->where('is_sent', false)
            ->get();

        foreach ($messages as $message) {
            // Log the message ID being dispatched
            \Log::info('Dispatching message ID: ' . $message->id);
            SendScheduledMessageJob::dispatch($message);
        }
    }
}

Console Route for Scheduling

<?php

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');

Schedule::command('app:send-scheduled-messages')->everyMinute()->description('Send scheduled messages');

SendScheduledMessageJob

<?php

namespace App\Jobs;

use App\Models\ScheduledMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class SendScheduledMessageJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $message;

    /**
     * Create a new job instance.
     */
    public function __construct(ScheduledMessage $message)
    {
        $this->message = $message;
        Log::info('Job created for message ID: ' . $this->message->id . ' with scheduled_at: ' . $this->message->scheduled_at);
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        DB::transaction(function () {
            try {
                // Log the start of message processing
                Log::info('Processing message ID: ' . $this->message->id);

                // Retrieve the messageable entity (the recipient)
                $messageable = $this->message->messageable;

                // Create a new message for the recipient with the content and sender ID
                $newMessage = $messageable->messages()->create([
                    'content' => $this->message->content,
                    'sender_id' => $this->message->sender_id,
                ]);

                // Check if the original message has attachments
                if ($this->message->attachments->isNotEmpty()) {
                    // Iterate through each attachment
                    foreach ($this->message->attachments as $attachment) {
                        // Generate a new path for the attachment, replacing the old message ID with the new one
                        $path = str_replace($this->message->id, $newMessage->id, $attachment->path);

                        // Determine the directory to remove after moving the file, up to "/attachments"
                        $path_to_remove = substr($attachment->path, 0, strpos($attachment->path, "/attachments"));

                        // Move the attachment to the new path
                        Storage::disk('public')->move($attachment->path, $path);

                        // Create a record for the attachment under the new message quietly (without raising events)
                        $newMessage->attachments()->createQuietly([
                            'path' => $path,
                            'name' => $attachment->name,
                        ]);

                        // Delete the old directory where the attachment was stored
                        Storage::disk('public')->deleteDirectory($path_to_remove);
                    }
                }

                // Mark the original message as sent
                $this->message->update(['is_sent' => true]);

                // Log the successful sending of the message
                Log::info('Successfully sent message ID: ' . $this->message->id);
            } catch (\Exception $e) {
                // Log any exceptions
                Log::error('Failed to send message ID: ' . $this->message->id . ', Error: ' . $e->getMessage());
            }
        });
    }
}

Additional Considerations

  • Database Locking: To avoid race conditions, consider using database locking mechanisms. This can help ensure that only one instance of the command processes a specific message at a time.
  • Job Queue Configuration: Ensure that your queue configuration is optimized for the frequency and volume of jobs you are dispatching. You might need to adjust the number of workers or the retry logic.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.