Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code only between certain hours

Tags:

php

I am trying to run a certain batch of code only during certain hours of the day. I want to run this code only after 8:00am and before 10:00 pm.

This code is included in the footer of my site, but it doesn't seem to be working, it is still running the code through these hours. (my server is in the same time zone as I am):

if(date("Hi") < 2200 && date("Hi") > 0800){
    // Run Code
}

How can I run the code only between the specific times?

like image 561
RandyLahey Avatar asked May 30 '13 15:05

RandyLahey


People also ask

How do I schedule a cron job daily?

Scheduling a Job For a Specific Time Add the below example to execute the specified log backup shell script at 11:00 on every day. We can specify the comma-separated value in a field specifies that the script needs to be executed in all the mentioned time.

Can I run cron job every minute?

“At every minute.” Cron job every 1 minute is a commonly used cron schedule. We created Cronitor because cron itself can't alert you if your jobs fail or never start.


3 Answers

if(date("Hi") < 2200 && date("Hi") > 800){
    // Run Code
}
like image 69
Ziarno Avatar answered Oct 05 '22 03:10

Ziarno


Try with strtotime function and relative formats:

if ( time() > strtotime( '08:00AM' ) && time() < strtotime( '10:00PM' ) ) {
    // run code
}
like image 33
Danijel Avatar answered Oct 05 '22 02:10

Danijel


Like Ryan said up in the comments - You need to set this up as a cron job.

http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/

to see your crons:

crontab -l

edit the crontab

crontab -e

an example cron that runs at 8am daily

00 08 * * * php path/to/script.php

The problem with setting it up the way you are attempting to is that every single request to your site is going to set off the event again (a possibility of mucking up the transactions)

like image 39
Francis Yaconiello Avatar answered Oct 05 '22 01:10

Francis Yaconiello