0

Is there a way in PHP to check if a function has completed processing before allowing it to run again?

I have a function that on page loads/reloads/timer event checks if DB items should be expired based on an end date (date less than now) and if date is less than now makes a duplicate of the record with the exact same information but adds 10 days to the end date. The script then sets the original record status to inactive. This is required to keep an original copy of the item in the DB and the process continues for every record.

Sometimes the script will create multiple duplicates of the same item so it seems like the script is not setting the status to inactive quick enough and when the page is reloaded/visited etc another instance of the script is run producing another duplicate record.

So is there a way to check if a function is currently running and if so ignore the new call to only ever have a single instance running?

Many many thanks

2
  • just set a flag at the end of the function Commented Jan 5, 2013 at 7:20
  • @Mr.Alien: Won't work, they're separate processes. Commented Jan 5, 2013 at 7:22

3 Answers 3

3

Sounds like you need a "mutex". You can try using this, or implement one yourself by creating a shared resource, such as writing an empty file to disk and then checking for its existence, and removing it when you're done.

A better solution for your specific problem though would be to set up a cron job to periodically run your database maintenance scripts rather than relying on random user requests to your page. This will ensure it won't run too often and reduce the processing per request.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that. Unfortunately I can't just have a cron job as the website is an auction site where items need to be updated and expired live and relisted live too. I will have a look at mutex but sounds like a good option
Hi, I have been trying to find some examples on how to use mutex but unable to find any that show complete code so I am a little confused about how to implement this. Do you have any examples that show how to do this? Thanks
0

For PHP:

 $Running = false;

   function functionName() {
    if (!$Running) {
        $Running= true;

        //Your logic implementation here

        $Running= false;
     }
  }

You can use same principle for jQuery functions also and cron job too.

Comments

0

Use a try catch

function blah() {
 try {
 }
 catch(Exception $e) {
  echo 'Message: ' .$e->getMessage();
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.