简体   繁体   English

每X秒执行一次PHP循环

[英]Perform a PHP loop every X seconds

I have the user type in how often they want a message sent as defined by the $time variable 我让用户输入他们希望发送消息的频率,如$ time变量所定义

This is the loop code I have right now 这是我现在拥有的循环代码

$time = $_POST["time"];

for ($x = 0; $x < $amount; $x++) {
    mail($completenum, $subject, $message, $headers);
    sleep($time);

}

The issue with this code is that the messages never get sent through, I believe it's because the sleep function halts the script. 这段代码的问题是消息永远不会发送出去,我相信这是因为sleep函数会暂停脚本。 Any ideas? 有任何想法吗?

PHP isn't really the correct language for this, you want to try javascript or similar. PHP并不是真正正确的语言,您想尝试javascript或类似语言。

PHP is designed to let you dynamically build a page when it is loaded. PHP旨在让您在加载页面时动态构建页面。 By putting a sleep in there, you're delaying the load time of the page, and the server and/or browser is eventually going to time out - pages aren't expected to take excessively long times to load, and that usually indicates an error. 通过在其中进行睡眠,您将延迟页面的加载时间,并且服务器和/或浏览器最终将超时-预计页面加载时间不会太长,这通常表明错误。 Different browsers are going to do different things, and you'd need to modify the timeout settings on everything if the delay is a long one. 不同的浏览器将执行不同的操作,如果延迟时间较长,则您需要修改所有内容的超时设置。

A scripting language that keeps running in the browser is going to be able to kick something off periodically like you want, and even update the page - you want code that keeps executing AFTER the page is loaded. 始终在浏览器中运行的脚本语言将能够像您希望的那样定期启动某些程序,甚至更新页面-您希望代码在页面加载后继续执行。

Alternately, if you want PHP only, your PHP code could store the request in a database, and then you could have another 'processing' page that you hit periodically with a cron job or similar in the background, which sends out the emails as per the time delay. 或者,如果您只想使用PHP,则您的PHP代码可以将请求存储在数据库中,然后您可以拥有另一个“处理”页面,该页面会定期在后台执行cron作业或类似操作,并按照时间延迟。 There are ways to achieve what you want with PHP only, depending on the actual end result you're after, but putting a sleep() into the loading of a page like this is unlikely to be a reliable solution. 有多种方法可以仅使用PHP来实现所需的功能,具体取决于要获得的实际最终结果,但是像这样将sleep()放入页面加载中可能不是一个可靠的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM