我想在收到'开放'GET请求后30分钟发送推文。我的Raspberry Pi在冰箱门打开时发出“打开”请求,在门关闭时发出“关闭”。时间框架应该可以防止人们忘记冰箱的门打开。我怎么能用PHP做到这一点?
<?php
require_once 'src/twitter.class.php';
$devicename = $_GET["devicename"];
$action = $_GET["action"];
// If device name and action is not empty
if (!empty($devicename) && !empty($action)) {
// Create database connection
require_once 'db_connect.php';
// Get all info related to received device name
$query = "SELECT * FROM devices WHERE devicename='$devicename'";
$result = mysqli_query($con, $query);
// If result is useful
if ($result) {
$row = mysqli_fetch_assoc($result);
$consumerkey = $row["consumerkey"];
$consumersecret = $row["consumersecret"];
$accesstoken = $row["accesstoken"];
$accesstokensecret = $row["accesstokensecret"];
$message = null;
// If GET parameter has value 'open'
if ($action == 'opened') {
// Get related message from database info and send tweet with related tokens
$message = $row["message1"];
send_tweet($consumerkey, $consumersecret, $accesstoken, $accesstokensecret, $message);
} else if ($action == 'closed') {
$message = $row["message2"];
send_tweet($consumerkey, $consumersecret, $accesstoken, $accesstokensecret, $message);
} else {
echo "<script type='text/javascript'> alert('Error at sending tweet! Check your GET parameters!'); </script>";
}
}
mysqli_close($con);
}
function send_tweet($consumerkey, $consumersecret, $accesstoken, $accesstokensecret, $message) {
$twitter = new Twitter($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
// Get local time and date
$datetime = date("d-m-Y H:i:s");
try {
// Send tweet with local time and date and message
$tweet = $twitter->send($datetime . ' ' . $message);
}
catch (TwitterException $e) {
echo '<script type="text/javascript">alert("Error:' . $e->getMessage() . '"); </script>';
//echo 'Error: ' . $e->getMessage();
}
}
?>
答案 0 :(得分:1)
不要将其视为一个单一过程,而是将其视为两个过程。
On process只检测打开/关闭事件。
其他流程推文,如果这是一个开放的事件而没有超过30分钟的关闭事件
您刚刚将第一个进程插入数据库中的日期和事件,并由GET请求执行。
第二个进程检测是否需要发送推文,并且可以每5分钟或每分钟通过一个cronjob执行。此过程仅检查数据库中是否存在没有关闭事件的打开事件,以及是否在30分钟或更长时间之前创建了此打开事件。只需检查每个设备的最后一个事件是否是一个打开的事件,你可以在一个名为tweeted的列中设置此事件是否已被发送。
Table event:
id: INT autoincrement
event: ENUM(open, closed)
date_created: DATETIME
tweeted: INT
$sql = 'SELECT * FROM events WHERE device = $device ORDER BY date_created DESC LIMIT 1;'
$result = mysqli_query($con, $sql);
if ($result){
$row = mysqli_fetch_assoc($result);
if ($row['event'] == 'open' &&
$row['tweeted'] == 0 &&
$row['date_created'] < date("Y-m-d H:i:s", strtotime("-30 minutes"))){
// Send tweet
// Update row with tweeted = 1 to not tweet it twice
}
}