dythffvrb
dythffvrb

Reputation: 177

cronjob. run php only in a specified interval of time

I have set up a cronjob that excutes a php script every 35 minutes. The issue is that I only want it to run from 11 AM to 2 AM the next day. I want this to be automatic without having to add # manually to the crontab.

I've tried putting something like this at the top of the php script :

$time = date(H);

if ($time < 23 & $time > 11)
{
   echo 'Working';
}
else
{
   echo 'Stopped';
} 

But as you can see that only works on the same day.

NOTE The server is using another time zone which has +4 hours of difference with mine.

That means: 11 AM local time is 3 PM server time and 3 AM next day local means 7 AM next day server.

Upvotes: 1

Views: 1461

Answers (4)

Melvyn
Melvyn

Reputation: 119

Let's take your code and apply some arithmetic, just substract 2 hours and you will have 9 to 23 instead of 11 to 23 + 0 to 2.

$time = date(H)  - 2 ;

if ($time < 23 & $time > 9 )
{
   echo 'Working';
}
else
{
   echo 'Stopped';
} 

Try!

I guess your timezone is GMT-4, so 11 am to 2 am on your timezone will be 15 am to 6 am on the server; the other posible setup is you're talking on server time, which mean 11 am to 2 am is 7 am to 10 pm on your setup.

This mean it's possible you must adjust the code to substract 6 hours instead of 2.

Upvotes: 0

AsOne
AsOne

Reputation: 51

shift the times to the correct timezone before checking.

Upvotes: 0

Timur
Timur

Reputation: 6718

You need to enclose H with quote marks:

$time = date("H");

Another way it is treated as constant, and, as you don't have such constant, date() receives empty argument

P.S. hohner provided better solution for you

Upvotes: 0

hohner
hohner

Reputation: 11578

So you want your cronjob to run between certain hours of the day? Have you tried:

35 11-23,0-2 * * * php /path/to/your/script.php

This will execute at 35 mins past every hour between 11am (day 1) and 2am (day 2) - everything is in server time.

Upvotes: 1

Related Questions