• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 212
  • Last Modified:

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
0
Jixit
Asked:
Jixit
  • 2
1 Solution
 
Roger BaklundCommented:
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';
0
 
Roger BaklundCommented:
For the file method you need to prevent a php error by using @:

$fh = @fopen('lockfile.txt','r');
0
 
JixitAuthor Commented:
Hi thanks for your comments! I will use the databse mechanism like you've explained! Thanks a lot for your help.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now