美文网首页
PHP+crontab 完美实现定时任务

PHP+crontab 完美实现定时任务

作者: 艾莉娅的缝衣针 | 来源:发表于2017-05-11 12:50 被阅读0次
PHP+crontab 完美实现定时任务

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

步骤

  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 "发送过了";
                        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!保存。

成功!

相关文章

网友评论

      本文标题:PHP+crontab 完美实现定时任务

      本文链接:https://www.haomeiwen.com/subject/xqjotxtx.html