0

I have a series of drivers for sending emails, for example Gmail, Yahoo, etc. The structure of the database:

drivers_table: 
id  name    host          status    user      pass
1   Gmail   google.com    1         user1     pass1
2   Yahoo   yahoo.com     1         user2     pass2

messages_table:
id     msg   driver_id     status
1      hi    null          0
2      hi2   null          0

I want to balance these messages and send them through Laravel and cran Jobs in a balanced way between the drivers.

My attempt to do so:

$schedule->job(new SendMessageCron())->everyMinute();

class SendMessageCron extends Command
{
 ....
  public function handle()
  {
    $dirvers = Driver::all();
    $msgs = Messages::all();
    foreach($dirvers as $driver) {
     SendMessageJob::dispatch($driver, $msgs);
    }    
   }
 
 }


php artisan queue:work

class SendMessageJob implements ShouldQueue
{
  use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  private $driver;
  private $messages;

  public function __construct( $driver, $messages)
  {
    $this->driver = $driver;
    $this->messages = $messages;
  }
  public function handle()
  {
    // email send code 
  }
 }

My questions are:
1- Is this structure correct?
2- Each submission made by SendMessageJob.php may take a long time and a new request will be sent to SendMessageJob.php again, but another driver is empty and can be sent and I do not want the request to be rejected, what should I do to do this?

Hossein
  • 67
  • 1
  • 9

1 Answers1

2

First, you should read here and learn about queues.

Your code has something missing:

$dirvers = Driver::all();
$msgs = Messages::all(); // here you are getting all messages

foreach($dirvers as $driver) {
 SendMessageJob::dispatch($driver, $msgs);
}    

You are getting all drivers and messages and sending them twice. Queue should process your code one by one (so you do not need to worry about if gmail or yahoo is free or not, queue will handle that)

here read queues and you can create 2 different queues 1 for gmail 1 for yahoo if you want an send your messages to them like :

SendMessageJob::dispatch()->onQueue('google');
SendMessageJob::dispatch()->onQueue('yahoo');

Of course you need add these queue configs too.

gguney
  • 2,512
  • 1
  • 12
  • 26
  • Thanks for the reply. Is my code structure correct for this job? – Hossein Mar 14 '22 at 09:04
  • I dont exactly know what are you trying to do but just create 2 queues and send your messages accordingly. If my answer helped you please do consider mark is an answer. – gguney Mar 14 '22 at 09:08