Do action once but only repeat it after x time - php

So basically, i need to notify a user if:
a) sensor disconnects and there hasn't been an alarm sent in last $send_threshold
b) if alarm sent on same day and greater than $repeat_threshold.
Example values of the variables
$send_threshold = 12 * 60; // 12 min
$repeat_threshold = 2 * 60 * 60 + 45 * 60; // 2 hr 45 min
I'm drawing a complete blank on how to make it happen. The sensors are stateless so there is no way for me to check if a sensor is online, other than to check timestamps of received data that the sensor posted to the api.
/* FUNCTIONS */
function handleDisconnectAlerts($sensor,$dataset,$users,$settings)
{
end($dataset);
$last_timestamp = $dataset[key($dataset)]['timestamp'];
$now = time();
if($now > $last_timestamp && $now - $last_timestamp > $settings['disconnect_alarm'] * 60)
{
$send_threshold = $settings['disconnect_alarm'] * 60;
$repeat_threshold = $settings['disconnect_alarm_repeat_hours'] * 60 * 60 + $settings['disconnect_alarm_repeat_minutes'] * 60;
//not really sure what to do from here.
}
}

Well, i figured it out myself i guess. The initial check covers the intial interval of 60 * $settings['disconnect_alarm']. From there i just needed to check that an alarm hasn't been sent in $repeat_threshold time. Works like a charm.
function handleDisconnectAlerts($sensor,$dataset,$users,$settings)
{
end($dataset);
$last_timestamp = $dataset[key($dataset)]['timestamp'];
$now = time();
if($now > $last_timestamp && $now - $last_timestamp > $settings['disconnect_alarm'] * 60)
{
$repeat_threshold = $settings['disconnect_alarm_repeat_hours'] * 60 * 60 + $settings['disconnect_alarm_repeat_minutes'] * 60;
$n_sent = R::count('sensoralerts',' timestamp >=:time and field_name="disconnect" and sensor_id=:id ',
[':time'=>$repeat_threshold,':id'=>$sensor['id']]
);
if($n_sent == 0){
multiSendDisconnect($users,$sensor);
}
}
}

Related

How to generate a random code for same email address after 20mins in php?

$fetch=mysql_query("select time from code where user_email='$email'");
$db_time=mysql_fetch_array($fetch);
$code= createRandomCode().time();
$current_time=date('Y-m-d H:i:s');
echo "present time".$current_time;
$time_string=strtotime($current_time);
//echo $time['time']."-".$time_string;
$time_diff=($time_string - $db_time);
echo $time_diff;
//if time difference is less than 60,then its seconds
if ($time_diff < 60) {
$result=$time_diff . " seconds";
echo $result;
}
//if time difference is greater than 60 and lesser than 60*60*60 ,then its minutes
if (($time_diff > (60)) && ($time_diff < (60 * 60 * 60))) {
$result=round($time_diff / (60 * 60)) . " minutes";
echo $result;
}
//if time difference is greater than 60*60*60 and lesser than 60*60*60*24,then its hours
if (($time_diff > (60 * 60 * 60)) && ($time_diff <= (60 * 60 * 60 * 24))) {
$result=round($time_diff / (60 * 60 * 60)) . " hours";
echo $result;
}
if ($time_diff > (60 * 60 * 60 * 24)) {
$result=round($time_diff / (60 * 60 * 60 * 24)) . " days";
echo $result;
}
Actually, im trying to generate a random code for all users.But the struggle is when the user enters the email id, the code has been generated,even they click it after a second, the new code is generated.Now that is the problem im facing.
I want that the every old user get his code after 20mins only.Please do some favour.
Since you want to send each user his code the best solution would be to use Cron Job (Scheduled Task).
This task could run every 2 minutes and send the code to all users which are valid for receiving a code.
You must create a task which will call your PHP script. An example:
*/2 * * * * /usr/bin/wget http://example.com/myscript.php >/dev/null
Here are some docs on Cron Job that will help you get started:
http://www.thesitewizard.com/general/set-cron-job.shtml
http://www.thegeekstuff.com/2011/07/php-cron-job/
If you choose this solution I would advice you to create a separate table which will be used only for storing [user_id, time_to_send_code].
Also don't forget to add indexes on your fields since it will be queried a lot.

I have a Broadcast system for in site talking to users,Keeps right time up till 24 hours. After the 24 hour max the time speeds up

$time_ago_op = time() - $comments[$c]['bcttime'];
if ($time_ago_op <= 60) { $comments[$c]['time_ago'] = $time_ago_op . " secs ago."; }
if ($time_ago_op >= 61 && $time_ago_op <= (60 * 60)) { $comments[$c]['time_ago'] = CleanNumber($time_ago_op / 60) . " mins ago."; }
if ($time_ago_op >= (1+(60 * 60)) && $time_ago_op <= (60 * 60 * 24)) { $comments[$c]['time_ago'] = CleanNumber($time_ago_op / (60 * 60)) . " hours ago."; }
if ($time_ago_op >= (1+(60 * 60 * 24)) && $time_ago_op <= (60 * 60 * 24 * 7)) { $comments[$c]['time_ago'] = CleanNumber($time_ago_op / (60 * 60 * 7)) . " days ago."; }
unset($time_ago_op);
After it a user posts it keeps the right time in seconds to minutes and hours, Once it hits 24 hours the time speeds up. For example a post that is 28 hours old says 3 days old and such... I am trying to figure out how to get it to keep the correct time and I am not having any luck.. If anyone can help and point out what I have set wrong it would help out a lot. Thanks
The issue is you are using just pure if blocks. You need to use PHP's if else construct.
Further imagine this scenario. The third if block is at the last nano second before it will trigger the fourth if block. The third will fire off, and then immediately fire the fourth, this can/will cause incorrect calculations.
EDIT
Why don't you just do something like this:
date_default_timezone_set("bcttime"); // whatever the correct time zone is
$server_time= date('G:ia');
$comment_time = $server_time - $comments[$c]['bcttime'];
// display the time with formatting

Date Difference in days in php

I have a function to calculate the difference between two dates.
function getDateDifference($to, $from, $in) {
$diff = abs($to - $from);
$years = floor($diff / (365 * 60 * 60 * 24));
$months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
$days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
if ($in == "days") {
return $days;
} else if ($in == "months") {
return $months;
} else if ($in == "years") {
return $years;
}
}
For the parameters i first convert the two dates into seconds like this,
checkin = '2012-07-26';
checkout = '2012-07-27';
check_in_date = strtotime(checkin);
check_out_date = strtotime(checkout);
im getting the correct difference when it comes to difference less than one month. But if the difference is more than one month, im always getting the difference as 1. Can someone tell me wat the problem is.
Currently, a month is always 30 * 60 * 60 * 24 sec, aka 30 days.
Your problem is that we're in July, and there are 31 days, not 30. You must take care of number of days per month.
You can make use of the DateTime class.
http://php.net/manual/en/datetime.diff.php
$checkin = new DateTime("2012-07-23");
$checkout = new DateTime("2012-07-27");
$difference = $checkin->diff($checkout);
echo "differrence = " . $difference->format('%R%a days');

Calculate total seconds in PHP DateInterval

What is the best way to calculate the total number of seconds between two dates? So far, I've tried something along the lines of:
$delta = $date->diff(new DateTime('now'));
$seconds = $delta->days * 60 * 60 * 24;
However, the days property of the DateInterval object seems to be broken in the current PHP5.3 build (at least on Windows, it always returns the same 6015 value). I also attempted to do it in a way which would fail to preserve number of days in each month (rounds to 30), leap years, etc:
$seconds = ($delta->s)
+ ($delta->i * 60)
+ ($delta->h * 60 * 60)
+ ($delta->d * 60 * 60 * 24)
+ ($delta->m * 60 * 60 * 24 * 30)
+ ($delta->y * 60 * 60 * 24 * 365);
But I'm really not happy with using this half-assed solution.
Could you not compare the time stamps instead?
$now = new DateTime('now');
$diff = $date->getTimestamp() - $now->getTimestamp()
This function allows you to get the total duration in seconds from a DateInterval object
/**
* #param DateInterval $dateInterval
* #return int seconds
*/
function dateIntervalToSeconds($dateInterval)
{
$reference = new DateTimeImmutable;
$endTime = $reference->add($dateInterval);
return $endTime->getTimestamp() - $reference->getTimestamp();
}
DateTime::diff returns a DateInterval object between 2 dates.
The DateInterval object gives all the informations (the number of days, hours, minutes, seconds).
Here's a sample code:
/**
* intervalToSeconds
*
* #param DateInterval $interval
* #return int
*/
function intervalToSeconds(\DateInterval $interval) {
return $interval->days * 86400 + $interval->h * 3600 + $interval->i * 60 + $interval->s;
}
$date_1 = new \DateTime('2021-03-03 05:59:19');
$date_2 = new \DateTime('now');
$interval = $date_1->diff($date_2);
echo intervalToSeconds($interval);
You could do it like this:
$currentTime = time();
$timeInPast = strtotime("2009-01-01 00:00:00");
$differenceInSeconds = $currentTime - $timeInPast;
time() returns the current time in seconds since the epoch time (1970-01-01T00:00:00), and strtotime does the same, but based on a specific date/time you give.
static function getIntervalUnits($interval, $unit)
{
// Day
$total = $interval->format('%a');
if ($unit == TimeZoneCalc::Days)
return $total;
//hour
$total = ($total * 24) + ($interval->h );
if ($unit == TimeZoneCalc::Hours)
return $total;
//min
$total = ($total * 60) + ($interval->i );
if ($unit == TimeZoneCalc::Minutes)
return $total;
//sec
$total = ($total * 60) + ($interval->s );
if ($unit == TimeZoneCalc::Seconds)
return $total;
return false;
}

The time function in php and 1969

I am trying to save the time in the database for when a user add an entry. Every time I run the time() function it prints (or returns) 1277155717 which represents 1969.
I was wondering if there is a way to save the time to the database in a way that it represents the actual date today at this moment.
I am using the function
/* Works out the time since the entry post, takes a an argument in unix time (seconds) */
function time_since($original) {
// array of time period chunks
$chunks = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute'),
);
$today = time(); /* Current unix time */
$since = $today - $original;
// $j saves performing the count function each time around the loop
for ($i = 0, $j = count($chunks); $i < $j; $i++) {
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
// finding the biggest chunk (if the chunk fits, break)
if (($count = floor($since / $seconds)) != 0) {
// DEBUG print "<!-- It's $name -->\n";
break;
}
}
$print = ($count == 1) ? '1 '.$name : "$count {$name}s";
if ($i + 1 < $j) {
// now getting the second item
$seconds2 = $chunks[$i + 1][0];
$name2 = $chunks[$i + 1][1];
// add second item if it's greater than 0
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
$print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
}
}
return $print;
}
In order to display the number of minutes, years, months, etc since the comment was posted and it is returning (40 years, 6 months ago) when I pass the value of the function time();
Why won't you just use sql's timestamp type, i.e.
INSERT INTO posts (content, created) VALUES ("Sample post", NOW());
Are you wanting a timestamp or the actual formatted time?'
If it's the latter, try this:
$time = date("h:i:s");
Be very careful before you start implementing your own date calculations. There are always weird cases to deal with. In your example, it looks to me like you aren't taking into account daylight savings time or leap years. I don't know if that matters to you.
Your chances are better if you use some library to do the date calculations for you. I would suggest you start by looking at the date_diff function in PHP. I don't know whether it handles daylight savings and leap years, but that's where I would start.

Categories