doonbfez815298 2016-03-18 08:12
浏览 151

防止PHP脚本同时运行多次的最佳方法?

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?

  • 写回答

1条回答 默认 最新

  • dongya8378 2016-03-18 08:21
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致