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!保存。

成功!


换一个访问我的blog: yondu.vip

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值