cronjob. run php only in a specified interval of time

跟風遠走 提交于 2019-12-13 18:21:44

问题


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.


回答1:


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.




回答2:


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




回答3:


shift the times to the correct timezone before checking.




回答4:


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.



来源:https://stackoverflow.com/questions/14914571/cronjob-run-php-only-in-a-specified-interval-of-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!