Prevent Cronjob PHP script to run simultaneously with another PHP script

Posted on 2008-11-19
Last Modified: 2013-12-13

I have a problem where clients are paying for a membership and while that script is processing the payment, a cronjob kicks in at the same time. This results in an unwanted duplicate transaction. Is there a way to prevent the cronjob from running, while the other script is still running?

Hope someone can help.

Question by:Jixit
    LVL 39

    Expert Comment

    by:Roger Baklund
    You need some sort of locking mechanism. One way to do this is using a database table. Another way is to use a file. Both ways could cause problems if the machine crashes during the running of the script, or if the script crashes. Then you would need to remove the lock manually.

    Using the database, SQL code:

      CREATE TABLE CronLock (locked int);
    set lock:
      INSERT INTO CronLock set locked=1;
      DELETE FROM CronLock;
    check for lock:
      SELECT * FROM CronLock;

    Using a file, PHP code:
    set lock:
      $fh = fopen('lockfile.txt','w');
    check for lock:
      $fh = fopen('lockfile.txt','r');
      if($fh) echo 'locked!';
      else echo 'open';
    LVL 39

    Accepted Solution

    For the file method you need to prevent a php error by using @:

    $fh = @fopen('lockfile.txt','r');

    Author Comment

    Hi thanks for your comments! I will use the databse mechanism like you've explained! Thanks a lot for your help.

    Featured Post

    What Is Threat Intelligence?

    Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

    Join & Write a Comment

    Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
    Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
    Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
    The viewer will learn how to count occurrences of each item in an array.

    731 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now