title: PHP: How to prevent multiple execution of a code (if it is already in process)
body: <h3>Explanation</h3>
  <p>An API call (to another service) which usually takes 10-20 seconds to respond is stored in database,</p>
  <p>After it is stored, System will try to use the API instantly to show the result to user, but it might fail (and display that it failed but we will try again automatically), therefore there is also a <code>Cron Job</code> set to run every 30 seconds and try the (failed) queries again.</p>
  <p>If the API return success (whether in instant usage or using Cron Job) the flag is changed to success in database and it will not run again.</p>
  <h3>Issue</h3>
  <p>My problem is while the <code>Instant Call</code> to API is in process, the <code>Cron Job</code> might also try another call as it is not yet flagged as successful,</p>
  <p>Also in rare cases, while the previous Cron Job is in process, the next Cron Job might run the code again.</p>
  <h3>What I have already tried to prevent the issue</h3>
  <p>I tried storing <code>In Process</code> API calls in a database table with <code>Status=1</code> and delete them when the API call was successful or set status to 0 if it failed,</p>
  <pre><code> if ($status === 0)
   {
       
       // Set Status to 1 in Database First (or die() if database update failed)
       
       // Then Call The API
  
       // If Failed Set Status to 0 so Cron Job can try again
       
       // If Successful Change Flag to success and remove from queue
  
   }
       
  </code></pre>
  <blockquote>
  <p>But what if the <code>Instant Call</code> and the <code>Cron Job Call</code> happen at the exact same time? they both check if status is 0 which it is, then both set status to 1 and execute the API Call...</p>
  </blockquote>
  <h3>Questions</h3>
  <ol>
  <li><p>Is what I have tried the correct way to handle this?</p>
  </li>
  <li><p>Should I worry about them happening at the exact time (the issue i explained in the Yellow Quote above) if there are a lot of calls (sometimes +500/sec)</p>
  </li>
  </ol>
  <h3>Update Before Bounty</h3>
  <p>Isn't there really an easy way to handle such cases on the PHP side? if not, which way is better in experts' opinion? below are some methods but none of them are detailed enough and none of them have any Downvotes/Upvotes.</p>
  <p>P.S. There are many updates/inserts to database, I don't think locking is an efficient idea and I'm not sure about the rest of ideas.</p>