让PHP文件每隔几秒执行一次

转自:http://www.blhere.com/966.html

背景是这样的:我需要一段PHP代码去定期对数据库操作,并把结果保存起来。如果方法是用户请求的时候来触发执行这个代码,显然用户的响应时间变长,影响用户体验!如果利用操作系统的定时任务,执行频率也是非常高的。

下面写个简单例子来讲解这个方法。

1
2
3
4
5
6
7
8
9
10
<?php
ignore_user_abort ( ) ; //关闭浏览器仍然执行
set_time_limit ( 0 ) ; //让程序一直执行下去
$interval = 3 ; //每隔一定时间运行
do {
    $msg = date ( "Y-m-d H:i:s" ) ;
    file_put_contents ( "log.log" , $msg ,FILE_APPEND ) ; //记录日志
    sleep ( $interval ) ; //等待时间,进行下一次操作。
} while ( true ) ;
?>

需要说明的是:程序没有写结束判断语句,他会无限循环下去。当然如果想停止的话,可以重启apache,重启后就无效了。想再次进行定时执行,那么把这段代码再一次运行。

上面简单例子可以说明这个原理。
那么针对上面的例子,我可以进行一下改良方案。

你需要一个执行脚本的开关,你可以用外部文件引入的方法来实现,在while循环的时候,include开关变量即可。那么就可以这样实现:
建立外部引入变量文件 switch.php 内容如下:

1
2
3
<?php
return 1 ; //1执行脚本 0退出执行脚本
?>

改良脚本如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
    ignore_user_abort ( ) ; //关闭浏览器后,继续执行php代码
    set_time_limit ( 0 ) ; //程序执行时间无限制
    $sleep_time = 5 ; //多长时间执行一次
    $switch = include 'switch.php' ;
    while ( $switch ) {
        $switch = include 'switch.php' ;
        $msg = date ( "Y-m-d H:i:s" ) . $switch ;
            file_put_contents ( "log.log" , $msg ,FILE_APPEND ) ; //记录日志
        sleep ( $sleep_time ) ; //等待时间,进行下一次操作。
    }
    exit ( ) ;
   
?>

转载于:https://www.cnblogs.com/lvchenfeng/p/5260543.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Scala语言实现上述需求可以借助以下技术: 1. 定时器:使用Scala内置的`scala.concurrent.duration`库来设置定时器,每隔一段时间执行特定的代码块。 2. 文件操作:使用Scala内置的`java.io`库来读写文件。 3. 随机数生成器:使用Scala内置的`scala.util.Random`库来生成随机数。 4. 单词计数器:使用Scala内置的`scala.collection.mutable.Map`来统计单词出现次数。 下面是一个简单的实现示例: ```scala import java.io.{File, PrintWriter} import scala.collection.mutable import scala.concurrent.duration._ import scala.util.Random object FileGenerator { val dirPath = "data" // 目录路径 val interval = 5.seconds // 文件生成时间间 val wordCountInterval = 10.seconds // 单词计数时间间 val totalCountInterval = 10.seconds // 总计数时间间 val wordCount = mutable.Map[String, Int]() // 单词计数器 var totalCount = 0 // 总计数器 def main(args: Array[String]): Unit = { // 创建目录 val dir = new File(dirPath) if (!dir.exists()) { dir.mkdir() } // 启动定时器 system.scheduler.schedule(0.seconds, interval) { generateFile() } system.scheduler.schedule(0.seconds, wordCountInterval) { countWords() } system.scheduler.schedule(0.seconds, totalCountInterval) { saveTotalCount() } } // 生成文件 def generateFile(): Unit = { val fileName = Random.alphanumeric.take(10).mkString // 随机生成文件名 val filePath = s"$dirPath/$fileName.txt" val writer = new PrintWriter(new File(filePath)) for (i <- 1 to 100) { val words = Random.alphanumeric.take(10).mkString(" ") // 随机生成单词 writer.println(words) } writer.close() } // 统计单词出现次数 def countWords(): Unit = { val files = new File(dirPath).listFiles().filter(_.isFile) val newWords = mutable.Map[String, Int]() for (file <- files) { for (line <- io.Source.fromFile(file).getLines()) { val words = line.split(" ") for (word <- words) { if (!wordCount.contains(word)) { newWords.put(word, 1) } else { wordCount.put(word, wordCount(word) + 1) } } } } println(s"New words count: ${newWords.size}") } // 统计总出现次数并保存到文件 def saveTotalCount(): Unit = { val total = wordCount.values.sum totalCount += total val writer = new PrintWriter(new File("total_count.txt")) writer.println(s"Total count: $totalCount") writer.close() } } ``` 该示例程序开启三个定时器:文件生成定时器、单词计数定时器和总计数定时器。文件生成定时器每隔一定时间在目录下生成一个文件文件名随机生成,文件中包含一些随机生成的英文语句。单词计数定时器每隔一定时间统计最近生成的文件中新出现的单词数量,并更新单词计数器。总计数定时器每隔一定时间统计所有单词的累计出现次数,并将结果保存到本地文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值