重复执行服务器端PHP脚本[关闭]

问题描述 投票:-1回答:1

我正在用PHP编写一个小脚本,如果发生某些天气情况,它将向我发送电子邮件或电报消息。我当时想每小时运行一次。

我的问题是,如果天气状况持续,我只需要收到一条通知。比方说,如果我收到下雪通知,那么在接下来的12小时内我不希望收到任何其他通知。

您将如何使用PHP解决此类问题?

php openweathermap
1个回答
0
投票
<?php
//Run script every hour with server command

$weather_array = [];

//Assume you'd pull these values from some kind of weather API, hypen added to the end so we can explode the array later.
$weather = "snow";
$weather_save = "snow" . "-";
$timestamp = date("Y-m-d H:i:s");

$weather_array[0] = $weather_save;
$weather_array[1] = $timestamp;

$file = "weather.txt";

if (!file_exists($file)) {
    file_put_contents($file, $weather_array);
}

$current_file = file_get_contents($file);

$weather_array2 = explode("-", $current_file);

$weather_new = $weather_array2[0];
$timestamp_new = $weather_array2[1];

if ($weather_new !== $weather_save) {

    //Enter send email script here alerting new weather condition

    //Delete weather.txt and recreate it with new $weather_array
    unlink($file);
    file_put_contents($file, $weather_array);

}

else {
    //The timestamp in the file plus 12 hours
    $future_time = date($timestamp_new, strtotime("+12 hours"));

    //if now is greater than or equal to the future timestamp
    if ($timestamp >= $future_time) {

        //Enter send email script here alerting weather condition remaining the same for 12 hours

        //Delete weather.txt and recreate it with the new $weather_array
        unlink($file);
        file_put_contents($file, $weather_array);
    }

    else {

        //Do nothing, 12 hours hasn't passed yet.
    }
}

?>
© www.soinside.com 2019 - 2024. All rights reserved.