How to run a specific condition in script after a specific time in php

I have two ad's and want to run them in difference of 8 hours, means ad1 start immediately when script start and ad2 start after 8 hour specified as 28800Seconds. I am seeking functions sleep() and time_sleep_until(), but bit confused how to use them between to ad's.

My ad's are defined in array. Also, i tried once sleep function in my localhost to execute one ad immediately and another one after sleep(28800), and script continues executing and displays the output of both ad's. It might be a small problem and i didn't apply logic properly.

Answers


It sounds like there is some confusion over what PHP is actually responsible for doing here. When somebody makes a request to the web server, a PHP script is being invoked, but then after serving the request, it is done and exits. When the next request comes in, it has no knowledge of the first request.

If you use the sleep(n) function to sleep for n seconds, that will pause the response of the web server, which is a very bad idea and not what you are trying to achieve.

Generally speaking, if you want to switch some content based on time, it is better to work off of the server time (which is always known) rather than something like "how long the server has been running" which has no meaning in the real world.

In a simple example, let's say you want to serve 3 different ads based on 8-hour blocks. You might write some code that finds the hour of day, and then selects an ad appropriately. For example:

$selection = (date('G',time()) / 8);
switch ($selection) {
  case 0:
    echo 'ad option 1!';
    break;
  case 1:
    echo 'ad option 2!';
    break;
  case 2:
    echo 'ad option 3!';
    break;
}

The date('G',time()) function returns the hour portion of the current system time which will be 0-23. Dividing that by 8 will give you either a 0, 1, or 2, and from there you can select what to display.

Not sure this will satisfy exactly what you are trying to do. If it does not, you may need to involve some kind of database, and have some kind of a job that updates the ad to serve at some interval (I'd avoid this if possible).


You should not run scripts for so long. Use cron instead. You can call the same script at 8 hours difference and based on a db switch call ad_1 or ad_2.


Need Your Help

Run configurations in maven

gwt maven jetty

I want to use maven to run my application in test mode. I have a multi module project which uses gwt. To debug my app I want to do the following:

How to fix/convert space indentation in Sublime Text?

sublimetext2 indentation auto-indent

Example: If I have a document with 2 space indentation, and I want it to have 4 space indentation, how do I automatically convert it by using the Sublime Text editor?