問題描述
是否有一種簡單的方法可以讓 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模板網!