在特定时间执行的 PHP 脚本

时间:2023-04-21
本文介绍了在特定时间执行的 PHP 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

是否有一种简单的方法可以让 php 脚本在一天中的特定时间执行一些 html?

Is there a simple way to have a php script execute some html at a certain times of the day?

例如,我的主页上有一个标题,有时我希望能够在标题下添加一些内容,在本例中为 iframe.

For example i have on my home page a header and at certain times i want to be able to add something right under the header, in this case a iframe.

我知道每个人都提到了 cron 工作,但这将如何工作?还有其他选择吗?并非在所有主机上都可用

I know everyone mentioned cron jobs but how would this work with that? also is there an alternative? Its not available on all hosting

推荐答案

cron 和计划作业的想法似乎与您实际尝试做的事情背道而驰.如果您只想在特定时间显示某些内容(在本例中为 iframe),您只需检查每个请求期间的服务器时间,并选择在给定时间段内显示它.

The idea of cron and scheudled jobs seems to run counter to what you're actually trying to do. If you want something to display (an iframe in this case) only during certain times, you can simply check the server time during each request, and opt to display it if you're within a given time period.

这样的事情将产生与 cron 作业相同的效果,但粒度更细,在发出请求的确切时刻检查时间.

Something like this will produce the same effect as a cron job, with more granularity, checking the time at the exact moment the requst is made.

<!-- Your Header here -->

<?php
$hour = date('G'); // 0 .. 23

// Show our iframe between 9am and 5pm
if ($hour >= 9 && $hour <= 17) { ?>
  <iframe .... ></iframe>
<?php } ?>

您可以扩展条件语句以每天多次显示 iframe,或者让您的脚本检查您希望用来管理 iframe 显示的任何外部条件.

You can expand on the conditional statement to show the iframe multiple times per day, or have your script check whatever external condition you're looking to use to govern the display of your iframe.

更新:可以通过诸如

<?php 
$hour = date('G');
$day  = date('N'); // 1..7 for Monday to Sunday

if (($hour >= 5  && $hour <= 7)  // 5am - 7am
||  ($hour >= 10 && $hour <= 12) // 10am - 12 noon
||  ($hour >= 15 && $hour <= 19) // 3pm - 7pm
||  ($day == 5)                  // Friday
) { ?>
  <iframe...></iframe>
<?php } ?>

使用服务器端 cron/任务调度程序作业定期从标头下方添加/删除 iframe 的想法比在每个请求期间简单地有条件地显示它要复杂得多.

The idea of periodically adding/removing the iframe from below your header with a server-side cron/task scheduler job is far more complex than simply conditionally displaying it during each request.

即使您有一些必须运行的特定任务,例如定期生成的报告,显示结果的实际工作通常也不会落在定期任务上.负责显示 iframe 的 PHP 脚本仍会在发出请求以显示任何新内容时查询数据库,并在找到时显示它,而不是定期任务以某种方式修改脚本以包含 iframe.

Even if you have some specific task which must run, such as a periodically generated report, the actual job of displaying the results usually don't fall upon the periodic task. The PHP script responsible for showing that iframe would still query the database at the time the request is made for any new content to show, and display it if found, rather than the periodic task somehow modifying the script to include an iframe.

这篇关于在特定时间执行的 PHP 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:在 mysql 和 php 中寻找空闲的时间块? 下一篇:PHP 时区列表

相关文章

最新文章