
圖片發(fā)自簡書App
PHP由于是順序執(zhí)行的腳本語言,多線程編程困難,因此PHP的定時任務相比較JAVA 困難的多,使用Sleep會導致性能極差和系統(tǒng)資源損失,下面我介紹一種高性能,又簡單的方式來解決這個問題。
步驟
- 編寫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"]);
}
}
}
}
}
- 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
- wq!保存。
成功!