PHP由于是顺序执行的脚本语言,多线程编程困难,因此PHP的定时任务相比较JAVA 困难的多,使用Sleep会导致性能极差和系统资源损失,下面我介绍一种高性能,又简单的方式来解决这个问题。

步骤

  1. 编写restful接口,可以用TP这样的框架,或者直接写PHP文件,完成任务逻辑。例如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    //使用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 "发送过了";
    continue;
    }
    $user = D("oauth_user")->find($uc["userid"]);
    $this->sendTemMsgForClassReminder($user["openid"], $course["id"], $uc["userid"]);
    }
    }
    }
    }
    }
  2. linux添加定时任务,crontab -e 编辑任务

    1
    2
    3
    4
    #每晚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
  3. wq!保存。

成功!