1

I have a long running script (anywhere from 30 to 160 seconds, based on settings) that requests data from an API using NuSOAP, based on this data it builds one big ~1000-4000 row insert query. It than truncates a table and inserts the big query.

When I run the scripts too closely timed one after the other it creates a problem where it loses data. I want to prevent this script from being run twice simultaneously.

This script will in the future also be run every ~5-10 minutes via cron/task scheduler.

Currently I block running the script simultaneously by checking if a file exists:

<?php
    header('content-type: application/json');
    ignore_user_abort(true);

    if (!file_exists('lock.txt')) {
        $lock = fopen('lock.txt','w');
        fclose($lock);

        //~450 API requests using NuSOAP.
        //TRUNCATE `table`
        //INSERT ~1000-4000 rows into `table

        $jsonArray = array(utf8_encode('script')=>utf8_encode('finished'));
        unlink('lock.txt');
    } else {
        $jsonArray = array(utf8_encode('script')=>utf8_encode('locked'));
    }
    echo json_encode($jsonArray);
?>

Is this a secure way of blocking a script from being run simultaneously? Is is better to check wether a MySQL column contains 'true' or 'false, instead of a file?

Is there a Better way?

displaynn
  • 23
  • 6
  • Use a database entry with a timestamp, that will be better. – shikhar Mar 18 '16 at 08:22
  • use transaction and store running state in a file/db. – Gogol Mar 18 '16 at 08:25
  • Could you not use a database transaction (and probably `DELETE` rather than `TRUNCATE`?) to just make sure your data doesn't end up in an inconsistent state? – Matt Gibson Mar 18 '16 at 08:25
  • What's the problem using the file approach? Seems good enough to me. It get's the job done, everything else is basically the same approach, you just move the information to another medium. Using the existence of a file, you could even use that file to store error-information. – Yoshi Mar 18 '16 at 08:28
  • Have you already had a look at [this way](http://stackoverflow.com/a/13837060/4153864) of using file locks ? – Dfaure Mar 18 '16 at 10:27
  • Yes this is better approach than db; – itzmukeshy7 Mar 18 '16 at 10:33

1 Answers1

0

I reckon lock file may not be the ideal, I would rather create a temporary session variable to check 'True' or 'False' to find whether the script running or not.

Optionally, I would also keep track of the actual time taken to execute each script which can be useful to check unnecessary time days and overall average time.

You should be still able to use the session even if you running the script via CRON Scheduler by manually assigning the session_id() before using session_start().

However, the Cookies will be browser dependent and it will not work with Cron.

rc.adhikari
  • 1,974
  • 1
  • 21
  • 24