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
Related
I am making a game mode in which I am trying to get the time a player has arrived at their destination after starting the mode and to do this I am using the insert of a date when it starts the mode it inserts a date and after reaching the your destination it registers another date and with both dates it calculates the time it took to get to the destination, with this I'm using date H:i:s (hours, minutes, seconds) but I need to take the time out and leave milliseconds after seconds example: i:s:u (minutes, seconds, milliseconds) but I'm not able to do this, I've tried it in several ways, basically everything works as follows:
1. I add in the player array a current date with hour, minutes, seconds;
$this->game[$player->getName()] = ["start" => strtotime('now')];
2. After the Player arrives at his destination he calculates the time of his trajectory creating another current date with already registered and using date and mktime to do the join and give a visual of time to the player;
$time = date('H:i:s', mktime(0, 0, str_replace("-", "", $this->game[$player->getName()]["start"] - strtotime('now'))));
3. Send the pretty message to the player about the time of his trajectory then time will be something like this: 01:45:23 (minute:seconds:milliseconds).
$player->sendMessage("You beat your time record by ".$time);
This is my method of doing, if you have another better method with the milli seconds added I accept the suggestion! Maybe there might be some errors in my code that I'm still not sure if they work correctly as the subtraction to calculate and join the current time with the previous one, tell me if it's right and if it is not correct correct me or do better. Thank you
Use microtime which returns the current Unix timestamp with microseconds
$game = [];
$game['start'] = microtime(true);
// Do stuff
sleep(3); // Without the sleep, start and end are the 'same'
$game['end'] = microtime(true);
$elapsedTime = ($game['end'] - $game['start']);
$minutes = floor($elapsedTime / 60);
$seconds = $elapsedTime % 60;
$milliseconds = number_format($elapsedTime - floor($elapsedTime),3);
Let's say I have a table and it consists a column of next_update (which is in a date format), time_left (which is in the unit of days). How could I program it for example the next_update is 27/02/14 and the time_left is 3 days for today(24/02/14) view in a php webpage but for tomorrow view in the php page will be automatically deducted to 2 days. I'm using postgresql as my database and php as the web interface. The main problem now is how can I make the value of time_left be minus by the next_update with the current date.
I've gone through some basic manual but still have no idea to set this up. Sincerely thank you all for any help.
Try this code
<?php
$now = time();
$next_update = strtotime("2014-02-27");
$datedifferent = $next_update - $now;
$days = floor($datedifferent/(60*60*24));
if($days > 0) {
echo $days.' more days you have';
}
?>
SELECT next_update, next_update - now() as time_left FROM <your_table>
You may also want to apply function EXTRACT to subtract necessary time units from interval (documentation)
I´m making a simple time management system feature and I want to add
task and estimated minutes.
So if I add into the field "finish sending e-mail to John" and "23" (as minutes) it goes into
mysql as $sql = "INSERT INTO schedule (task, time, timestamp) VALUES ('$_POST[task]','$_POST[time]','$_POST[timestamp]')";
The output would be " Finish sending e-mail to John 21:02 - 21:25 "
so if next task takes 7 minutes it will be from 21:26 - 21:33" (take notice
of the first task and so and and so forth
I tried echo date('H:i', strtotime('+["time"] minutes', ));
but it doesn´t
work and I don´t know how the next record would take notice of the next one
is this possible?
What you tried above is almost correct, except that you might mean $_POST['time'] instead of ["time"], making your code: echo date ('H:i', strtotime('+{$_POST["time"]} minutes'));. But that will give you the time minutes after current time, not after the starting time.
To get the end time, you need to convert your start time (I assume it's $_POST['timestamp']) into UNIX timestamp, then add the task's length and get the UNIX timestamp from it.
Give this a try:
// Remember to check for valid user input. I'll leave that for you.
$task = $_POST['task'];
$time = $_POST['time'];
$timestamp = $_POST['timestamp'];
// Get the time here
$start_time = date ("H:i", strtotime ($timestamp));
$end_time = date ("H:i", strtotime ($timestamp) + $time * 60);
echo "{$task} {$start_time}-{$end_time}\n";
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.
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.
I create the unix timestamp in a php file doing
$end = mktime(16, 54, 0, 8, 18, 2011);
and the copy it below
Countdown Script
<script type="text/javascript">
var end_date = new Date(<?php echo $end; ?>*1000);
$(document).ready(function() {
$("#time").countdown({
date: end_date,
onComplete: function( event ){
$(this).html("completed");
},
leadingZero: true
});
});
</script>
<p id="time" class="time"></p>
Instead of playing the heroes by trying to do time Math (and even failing badly), you should rely on native methods, available to both PHP and JS:
// gets the time 9 hours from now
// you can give a 2nd parameter to specify when is "now"
$date = strtotime('+9 hours');
and:
// get the time right now
var date = new Date()
// add 9 hours, don't worry about jumping the 24hr boundary, JS resolves correctly.
date.setHours(date.getHours()+9)
Edit:
Since the OP said he wanted to use a TS from DB, here's the relevant code:
$date = strtotime('+9 hours', (int)$db_time);
Note: If $db_time is a formatted string, like "24 April 2011, 4:56 pm", you need to put the following code before the one above:
$db_time = strtotime($db_time);
However, I urge you to check for alternative ways to parse the time.
I'm going to read between the lines here a bit. I assume based on this and previous questions that you want a countdown for some event in the future and you're pulling a timestamp from a database and adding 9 hours to it to get the time of that future event.
Assuming this, you can't use most (any?) of the previous answers because of time zones and the fact that the user's clock might be more or less off. So if you calculate on the server that the event should fire at 5 o'clock and send that info to the user who's 3 time zones away from the server, the countdown will also be 3 hours off (because when it's 5 o'clock where the user is it's either 2 or 8 o'clock where the server is.)
The solution is to calculate the time left until the event and send that information to the browser. This way the countdown will be independent of the user's timezone or their computer's clock. For example if the event is at 5 o'clock and it's now 4 o'clock tell the browser to put 60*60*1=3600 seconds on the timer.
Using part of Christian's answer, do something like this on the server (assuming $db_time contains a Unix timestamp retrieved from the database):
$date = strtotime('+9 hours', (int)$db_time);
$timeUntilEvent = $date - time();
Now $timeUntilEvent contains the amount of seconds until the event. In JavaScript add that number to the timer:
var end_date = new Date();
end_date.setTime( end_date.getTime() + <?php echo $timeUntilEvent; ?> * 1000 );
Now the timer will fire at the correct time regardless of what time the user's clock is set to.
var end_date = new Date((<?php echo $end; ?>+32400)*1000);
end_date = end_date + ((3600*1000)*9);
mktime returns seconds, so you simply add the desired amount of seconds
using the end_date created with php, add this line:
end_date+=9*60*60
Call this before your countdown:
end_date = end_date.setTime((end_date + (9 * 3600)) * 1000).toGMTString();
EDIT: I removed the get_time() and the "* 1000" as end_date is already a UNIX timestamp.
EDIT2: Apparently, timestamps in js are in milliseconds so we also have to multiply the PHP timestamp (which is in seconds).