PHP+crontab 完美實現(xiàn)定時任務

圖片發(fā)自簡書App

PHP由于是順序執(zhí)行的腳本語言,多線程編程困難,因此PHP的定時任務相比較JAVA 困難的多,使用Sleep會導致性能極差和系統(tǒng)資源損失,下面我介紹一種高性能,又簡單的方式來解決這個問題。

步驟

  1. 編寫restful接口,可以用TP這樣的框架,或者直接寫PHP文件,完成任務邏輯。例如:
//使用TP框架建立restful接口
class OauthController extends Controller
{
    /*
    完成上課提醒
    */
    public function classReminder()
    {
        //查看今天所有課程
        $courses = D("course")->where(array("cday" => date("Y-m-d")))->select();

        foreach ($courses as $course) {
            $cstime = strtotime($course['cstime']);
            $currtime = time();
            $cc = $cstime - $currtime;
            if ($cc < 60 * 60 && $cc > 5 * 60) {
                $ucc = D("user_card_course")->where(array("courseid" => $course["id"]))->select();

                foreach ($ucc as $uc) {
                    $re = D("wxmsg")->where(array("userid" => $uc["userid"], "courseid" => $course["id"], "type" => "上課提醒"))->find();
                    if ($re) {
                        echo "發(fā)送過了";
                        continue;
                    }
                    $user = D("oauth_user")->find($uc["userid"]);
                    $this->sendTemMsgForClassReminder($user["openid"], $course["id"], $uc["userid"]);
                }
            }
        }
    }
    }
  1. linux添加定時任務,crontab -e 編輯任務
#每晚2點備份mysql
0 2 * * *  /opt/mysqlBack/bkMysql.sh 
#每15分鐘(每小時的 0 15 30 45 分啟動),訪問接口,并將日志輸出到log
*/15 * * * * wget http://localhost/classreminder >/opt/server/gmfitness-schedule/classreminder.log 2>&1
  1. wq!保存。

成功!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容