Handle Queue race condition in PHP Symfony with MySQL Database
<p>I've an application in Symfony that needs to send Emails/Notificatios from the App.
Since the Email/Notifications sending process takes time, so I decided to put them in Queue and process the Queue periodically. Hence I can decrease the response time for the Requests involving the Email/Notification dispatch.</p>

<p>The Cron Job(a php script - Symfony route) to process the queue runs every 30 seconds, and checks if there are any unsent Emails/Notifications if found it gets all data from the Queue Table and starts sending them. When an Email/Notification is sent, the Queue Table row status flag is updated to show that it's sent.</p>

<p>Now, when there are more Emails in Queue which could take more than 30 seconds to send. Another Cron Job also start running and starts sending emails from the Queue. Hence resulting in duplicate Emails/Notifications dispatch.</p>

<p>My Table structure for Email Queue is as follows :</p>

<pre><code>|-------------------------------------|
| id | email | body | status | sentat |
|-------------------------------------|
</code></pre>

<p>My Ideas to resolve this issue are as follows : </p>

<ol>
<li>Set a flag in Database that a Cron Job is running, and no other Cron Jobs should proceed if found the flag set.</li>
<li>Update status as 'sent' for all records and then start sending Emails/Notifications.</li>
</ol>

<p>So my question is, are there any efficient approach to process Queues? Is there any Symfony Bundle/Feature to do such specific task? </p>