• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 215
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

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