Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

PHP script to execute at certain times

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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 } ?>

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.

Update: Additional times or types of comparisons could be specified via something like

<?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 } ?>

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...