PHP之定时任务(绝对实用)

在工作中经常会用到定时任务,除了在js中有定时器这个玩意可以用于前端页面的定时任务;

那么后端PHP如何设置定时任务呢?

一.如下是javascript中使用setTimeout和setInterval设置定时任务:

1 setTimeout(function () {
2     console.log('timeout');
3 }, 1000);
4 
5 setInterval(function () {
6     console.log('interval')
7 }, 1000);
8 
9 // 输出一次 timeout,每隔1S输出一次 interval

二.在PHP中使用一个死循环来设置定时任务:

<?php
ignore_user_abort();//关掉浏览器,PHP脚本也可以继续执行.
set_time_limit(0);// 通过set_time_limit(0)可以让程序无限制的执行下去
while(true){
  sleep(10);      //让程序睡10s,可以根据自己的逻辑设置时间
  $num = 10;
file_put_content('a.text',$num);//将内容写进a.text文件中
缺点: 启动之后,便无法控制, 除非终止 PHP 宿主. 一般不要采用这样方法.

三.使用crontab和php服务来定时执行php任务(在linux环境中)

首先介绍一下
crontab的常用命令:
/bin/systemctl start(stop/restart/status) crond.service
启动(停止、重启、状态)定时任务
Crontab -e
添加(删除)定时任务
Crontab -|
查看已经添加的任务

 

语法: minute hour day month dayofweek  command

 minute - 从0到59的整数 

 hour - 从0到23的整数 

 day - 从1到31的整数 (必须是指定月份的有效日期)

 month - 从1到12的整数 (或如Jan或Feb简写的月份)

 dayofweek - 从0到7的整数,0或7用来描述周日 (或用Sun或Mon简写来表示)

 command - 需要执行的命令(可用as ls /proc >> /tmp/proc或 执行自定义脚本的命令

注意:一般星期几和日期不同时使用,*代表是每,* * * * * 每分/每时/每天/每月/每星期几

具体步骤如下:

/root目录下新建hello.php文件;
chmod 777 hello.php 将文件更改为可执行的文件;
/bin/systemctl  start  crond.service 开启crontab服务;
④ 执行crontab -e;
⑤在列表中添加任务:* * * * * php  /root/hello.php >> /root/hello.text(设置为每分钟执行,并将hello.php的输出写入到hello.text文件中)

/bin/systemctl  start  crond.service重启crontab服务

注意:php文件需要用php去执行(重要);然后所有的路径都要写绝对地址。Hello.php写业务逻辑;
* * * * *所代表的含义,以及怎么设置时间如果还不清楚的话可以上网百度;

其实在linux下,上图这种方法是使用crontab+php命令去执行php文件;

二:将解析命令放在shell脚本中,crontab定时shell脚本来执行;

这一种方法是上一中方法的衍生.脚本如下:
#!/bin/bash
php /root/hello.php

然后,执行crontab -e;
* * * * * /bin/sh /root/hello.sh

这样,定时执行shell脚本,同时shell脚本执行php任务,等同于定时执行php任务;(复杂的业务逻辑就需要自己在php中去写)

注意:以上所有的路径都需要些绝对路径.(重要)


 
 
 
 
posted @ 2019-05-09 14:04  墙角摘蘑菇  阅读(18829)  评论(0编辑  收藏  举报