PHP脚本在特定时间执行 [英] PHP script to execute at certain times

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

问题描述

是否有一种简单的方法可以让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的想法要比在每个请求期间仅有条件地显示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脚本在特定时间执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆