Hello everyone,
I'm facing an issue with a Laravel console command designed to send scheduled messages, and I would appreciate any help or insights from the community.
Problem Description I've implemented a command that retrieves scheduled messages from the database and dispatches a job to send each message. While the first message is processed correctly, subsequent messages seem to use the previous iteration's values, leading to incorrect message dispatching.
Command Code Here's the code for the command:
<?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) {
SendScheduledMessageJob::dispatch($message);
}
}
}
and here is my console route for scheduling the task
<?php
use App\Models\ScheduledMessage;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schedule;
use Illuminate\Support\Facades\Storage;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote')->hourly();
Schedule::command('app:send-scheduled-messages')->everySecond()->description('Send scheduled messages');
and here is 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($this->message->scheduled_at);
}
/**
* Execute the job.
*/
public function handle(): void
{
DB::transaction(function () {
try {
// 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]);
} catch (\Exception $e) {
// Log any exceptions
Log::error('Failed to send message ID: ' . $this->message->id . ', Error: ' . $e->getMessage());
}
});
}
}
these are scheduled messages which were added to database with following scheduled_at values
and these are logs which were generated
[2024-07-03 14:08:00] local.INFO: 2024-07-03 12:14:00
[2024-07-03 14:08:00] local.INFO: 2024-07-03 12:14:00
[2024-07-03 14:08:00] local.INFO: 2024-07-03 12:15:00
[2024-07-03 14:08:00] local.INFO: 2024-07-03 12:16:00
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:
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.
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.
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.
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:
<?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);
}
}
}
<?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');
<?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());
}
});
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community