PHP – Scheduled code fragments or set code to be run in the future

Sometimes you may need a code which should be run in certain date interval. No, i don’t mean whole php file, for that there is a technology called “Cron Jobs”.
I mean code fragment in your existing PHP project.
For example you want you background to be red after 23:59. Or at 31st decebmer night you want some “happy new year” banner to be appear for 1-2 hours. Or you just creating some scheduled event module and this logic can help you build it.
Let’s write this simple trick.

set php code to be run in the future

<br />
$now_date=time();<br />
if ($now_date&gt;1475602004 and $now_date&lt;1475638904) {<br />
echo 'body {background: red}';<br />
}<br />

or we can use readable dates.
<br />
$now_date=time();<br />
$begdate=strtotime('2016-10-05 23:59:00');<br />
$enddate=strtotime('2016-10-06 01:59:00');<br />
if ($now_date&gt;$begdate and $now_date&lt;$enddate) {<br />
echo 'body {background: red}';<br />
}<br />

That’s all. This simple php code runs code fragment in the given datetime interval.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: