dongtuoji5396 2010-10-21 17:12
浏览 77
已采纳

在实时网站上只执行一次php脚本

I have a script that does an update function live. I would move it to a cron job, but due to some limitations I'd much rather have it live and called when the page loads.

The issue is that when there is a lot of traffic, it doesn't quite work, because it's using some random and weighted numbers, so if it's hit a bunch of times, the results aren't what we want.

So, question is. Is there a way to tell how many times a particular script is being accessed? And limit it to only once at a time?

Thank you!

  • 写回答

3条回答 默认 最新

  • douwei8672 2010-10-21 17:46
    关注

    You could do something like this (requires PHP 5):

    if(file_get_contents("lock.txt") == "unlocked"){
      // no lock present, so place one
      file_put_contents("lock.txt", "locked");
    
      // do your processing
      ...
    
      // remove the lock
      file_put_contents("lock.txt", "unlocked", LOCK_EX);
    }
    

    file_put_contents() overwrites the file (as opposed to appending) by default, so the contents of the file should only ever be "locked" or nothing. You'll want to specify the LOCK_EX flag to ensure that the file isn't currently open by another instance of the script when you're trying to write to it.

    Obviously, as @Pekka mentioned in his answer, this can cause problems if a fatal error occurs (or PHP crashes, or the server crashes, etc, etc) in between placing the lock and removing it, as the file will simply remain locked.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序