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.
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.
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
shift the times to the correct timezone before checking.
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.
Related
i have time shifts which are assigned to the user. Suppose a night shift starting time is 21-00-00 pm of one july and its ending time is 03-00-00 am of 2nd July. Now i want to get total time a employee worked by adding start time to end time which is equal to 6 hours and i should get six hours. I have tried following code which is working fine for current date like it will give me exact 6 hours if start time is equal to 15-00-00 pm of 1 july to 21-00-00 pm of 1 july but it will fail when shifts exists between two dates as i mentioned above.
$attendance_start_time = \Carbon\Carbon::parse($shift->start_time);
$attendance_end_time = \Carbon\Carbon::parse($shift->end_time);
$total_attendance_time=$attendance_end_time->diffInSeconds($attendance_start_time,true);
\Carbon\CarbonInterval::seconds($total_attendance_time)->cascade()->forHumans()
i am expecting six hours but it is giving me following result
18 hours
i want exact six hours
Not sure if it will fully solve your problem, but check out this :
\Carbon\CarbonInterval::seconds(4100)->cascade()->forHumans(['aUnit' => true]);
UPD:
It might be this solution will work in your case, but make sure that you have tested all of the edge-cases:
$startTime = \Carbon\Carbon::parse('2022-07-02 19:00');
$endTime = \Carbon\Carbon::parse('2022-07-02 19:30');
$diff = $startTime->diffInSeconds($endTime);
if ($endTime->greaterThanOrEqualTo($endTime) && ! $endTime->isSameDay($startTime)) {
$diff = $startTime->diffInSeconds($endTime->addDay());
}
$humanReadable = \Carbon\CarbonInterval::seconds($diff)->cascade()->forHumans(['aUnit' => true]);
I want to display content from the database with dates up to 2hours ahead of time.
Example:
2018-11-09 20:00:00.000000
2018-11-08 19:00:00.000000
2018-11-06 19:00:00.000000
2018-11-06 18:00:00.000000
Lets say the time and date is
Nov 6th at 6pm. I want the bottom two entries to be displayed and the two future dates to not show until the current time is within 2hours of that time.
My code is as follows:
$cT = strtotime($row3['MissionTime']) - strtotime("now");
if($cT <= strtotime('-2 hours')) {
echo $row3['MissionTime']."<br>";
}
I've tried several different ways but I can't seem to get this to work right. Help and tips?
The reason your code doesn't work is that strtotime returns a number of seconds since the unix epoch. When you subtract two results of strtotime you will get a number of seconds difference which is as you expect. However you cannot compare that value to strtotime('-2 hours') as the output of that will be the timestamp for 2 hours before now (which right now is 1541539906), so the test will always pass. You should just compare it to 7200 instead (I'm pretty sure based on your question description that +7200 is more appropriate than -7200). so change
if($cT <= strtotime('-2 hours')) {
to
if($cT <= 7200) {
Note that it is almost certainly better to do this in your query. Try adding a condition on your time column as something like
WHERE MissionTime <= NOW() + INTERVAL 2 HOUR
And then you won't need to check in the PHP at all.
strtotime() returns a timestamp in seconds. Subtracting two timestamps gives you a difference between those two timestamps, in seconds.
So if strtotime($row3['MissionTime']) is a timestamp that's 1.5 hours in the future, and you subtract strtotime("now") from it, you end up with a difference of 5400 seconds (60 seconds * 60 minutes * 1.5 hours).
strtotime('-2 hours') gives you the timestamp for 2 hours ago, which is currently somewhere around 1.5 billion. This is not very useful for your situation.
Here are two ways to modify your code:
$cT = strtotime($row3['MissionTime']) - strtotime("now");
if($cT <= 7200) {
echo $row3['MissionTime']."<br>";
}
If the difference between $row['MissionTime'] and now is less than 7200 seconds (60 seconds * 60 minutes * two hours), $row3['MissionTime'] is either in the past or it's within the next two hours.
Alternatively:
if(strtotime($row3['MissionTime']) <= strtotime('+2 hours')) {
echo $row3['MissionTime']."<br>";
}
Basically the same, but perhaps more readable if you're not planning to use $cT for anything else. This simply checks if $row3['MissionTime'] is earlier than whatever time it will be in +2 hours.
I was wondering if I could get some help.
I have a cronjob that is run every 5 mins.
I also have a number of entries in my DB with a 'start date' formatted like
'yyyy-mm-dd HH:mm:ss'
What I want to do is run a specific command for each entry 24 hrs after the start date.
So for instance, if an entry has a start date of 2016-11-18 12:08:44, I want to run a command on that entry at 2016-11-19 12:08:44 ... Because the cron only runs every 5 mins, I don't expect to be exactly spot on 24hrs, but as close (5 mins each way) as possible.
Is there any chance someone could give me an example of how I could achieve this in PHP?
Much appreciated.
You should do the job like this :
Add a column "desired launch date" in the DB (Nullable).
Write a php script what calculate all 'desired launch date' from 'start_date' (and update the DB with calculed date).
Add block on this PHP script that initialize current datetime and compare with 'desired launch date' with an interval of 10 minutes.
EDIT :
Here a piece of source code, not tested !
$datetime = new \Datetime();
$timestamp = $datetime->getTimestamp();
$datetime_desired_launch = new \Datetime($your_formatted_datetime_from_db);
$desired_timestamp = $datetime_desired_launch->getTimestamp();
// I have manipulate timestamp for more efficiency
$launch_min_interval = $desired_timestamp - 5 * 3600; // - 5 minutes
$launch_max_interval = $desired_timestamp + 5 * 3600; // + 5 minutes
if ($timestamp >= $launch_min_interval && $timestamp <= $launch_max_interval) {
// Here launch action...
}
Be careful of timezones !
Hope this help !
You can use crontab to lance a script each 5 min
In this script you can check for date and lance the others scripts
I need help.. Is this right?
Start Date: Mar 16, 2014
End Date: Mar 19, 2014
Results: 2 Days
$plantEnd = get_the_author_meta('plantEnd', $sellerID );
$plantStart = get_the_author_meta('plantStart', $sellerID );
$future = $plantEnd;
$d = new DateTime($future);
echo $d->diff(new DateTime())->format('%a').' Days';
Why does it says 2 days? Isn't it 3 days? Im confused..
Since you aren't actually using $plantStart in your code and instead using the current time, you're basically getting a difference between now (the time the script was run, on server's time zone) and the start of Mar 19, 2014 (0h:0m:0s). So what you are really getting is something like 2 days 5 hours 3 minutes 25 seconds (depending on when you run it vs. server time.
for example, when I run this locally:
$d->diff(new DateTime())->format('%d:%H:%i:%s');
I get 2:04:59:25
So there's more to it than just getting that "2" returned.. you're just not formatting for it.
And again, you aren't actually using the $plantStart anywhere either. So if you were to do this:
<?php
$plantEnd = '2014-03-19';//get_the_author_meta('plantEnd', $sellerID );
$plantStart = '2014-03-16'; //get_the_author_meta('plantStart', $sellerID );
$future = $plantEnd;
$d = new DateTime($future);
echo $d->diff(new DateTime($plantStart))->format('%d:%H:%i:%s');
?>
You will see it outputs 3:00:0:0 (or you could continue to just use %d and get the "3"). This is because $plantStart (presumably - based on your post) just specifies yyyy-mm-dd, so passing just the yyyy-mm-dd value will put the hh:mm:ss at 0:0:0 (beginning of day) , so it will be a full day's calculation, which has the effect of "rounding up" to the whole day increment.
I have a feeling that it's actually 2 days, someodd hours, and someodd minutes, or something to that effect. Because you're formatting to just do days, you're losing the nuances. I'd change the code to say "2.4 days" (and for the life of me I can't remember how I did this in the past...)
EDIT: in the past I have simply used date() instead of DateTime().
I did a little research, and you might want format('%d')." Days";
I have a list of timestamps that represent a list of backed up files. But to reduce the amount of space needed I only want to keep the files that are from around mid day- I have started writing a function check but got stuck on how could i check if the timestamp is between 12 and 1 for that day? I have a list of timestamps for many days.
function check_date($timestamp='')
{
if (($timestamp < strtotime("-1 week")) && (time is between 12 and 1 )){
}
else
remove
}
I wrote an answer to this previously, I will try find a link in a minute when im free but essentially get the timestamp for 12 and the timestamp for 1 then
if(timestamp12 < curTimestamp && curTimestamp < timeStamp1)
Then you know that the curTimeStamp is between 12 and 1.
Previous answer https://stackoverflow.com/a/11578345/1475461
The other question was for a javascript implentation but timestamp comparison works the same whether you are using PHP, javascript etc. since they are miliseconds/seconds since a set point in time (1st January 1970), so it is just a comparison of integers.
Okay, let me think...ah, here it is. Good old 'localtime' function.
http://www.php.net/manual/de/function.localtime.php
Run your timestamp through this function, then you can check the result.
$TimeInfo = localtime(timestamp, true);
if (($timestamp < strtotime("-1 week")) && $TimeInfo["tm_hour"] == 12) {
}
else remove
With this code, all files, which have arrived at 12:00, up to 12:59 (1 is excluded in this example) are preserved, the others get removed.