如何在X时间后仅发送一次电子邮件

问题描述:

I am making a PHP alarm notification that will send an email if a temperature set point has been reached.

I have CRONJOB that runs in every 1 minute, runs a PHP script that verifies the temperature and if the temperature reaches to a point, it will send an email notification to me.

The problem is, that it will send me a email notification every minute while the temperature is passed the set point due to the CRONJOB. I would like for it to only send me an email once. Not send one minute.

I am using MYSQL to store the alarm information. If I need to some how setup time stamp in mysql and have the script verify the time and send it during x amount of time.?

Thanks,

我正在制作一个PHP报警通知,如果达到温度设定点,将发送电子邮件。 p >

我有每1分钟运行一次的CRONJOB,运行验证温度的PHP脚本,如果温度达到某一点,它会向我发送电子邮件通知。 p>

问题是,由于CRONJOB温度超过设定值,它会每分钟发送一封电子邮件通知。 我希望它只向我发送一次电子邮件。 不发送一分钟。 p>

我正在使用MYSQL来存储警报信息。 如果我需要一些如何在mysql中设置时间戳并让脚本验证时间并在x时间内发送它。? p> nn

谢谢, p> div >

You could either do the calculation in your application code or directly in the DB. Here's some pseudo code.

Application Code

CONST NOTIFICATION_DURATION = '30 minutes';

$mostRecentNotification = query('SELECT MAX(created_at) FROM notifications');

// Notice we're doing the calculation in our application code.
$nextAvailableNotification = $mostRecentNotification + NOTIFICATION_DURATION;

if (current_time >= $nextAvailableNotification) {
    send_notification();
}

If you choose to go with the application code version, I highly recommend using a library like Carbon (https://carbon.nesbot.com/) to help you out with your date/time arithmetic. It truly is a life saver even with simple calculations like this one.

Database Version

CONST NOTIFICATION_DURATION = '30 minutes';

// Notice we're doing our calculation in our database
$nextAvailableNotification = query('SELECT MAX(created_at) + INTERVAL ' . NOTIFICATION_DURATION . ' FROM notifications');

if (current_time >= $nextAvailableNotification) {
    send_notification();
}

You could further compress the database version by doing the comparison directly in your query but I'll leave that up to you.