Link to home
Start Free TrialLog in
Avatar of Jixit
Jixit

asked on

Prevent Cronjob PHP script to run simultaneously with another PHP script

Hi,

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.

Jikke
Avatar of Roger Baklund
Roger Baklund
Flag of Norway image

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:

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

Using a file, PHP code:
set lock:
  $fh = fopen('lockfile.txt','w');
  fwrite($fh,'locked');
  fclose($fh);
unlock:
  unlink('lockfile.txt');
check for lock:
  $fh = fopen('lockfile.txt','r');
  if($fh) echo 'locked!';
  else echo 'open';
ASKER CERTIFIED SOLUTION
Avatar of Roger Baklund
Roger Baklund
Flag of Norway image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jixit
Jixit

ASKER

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