php定时任务一般写什么功能,PHP-PHP怎么写定时任务?

如果可以使用 cli 模式的话,那么完全可以使用 php xx.php 的形式来执行计划任务,使用set_time_limit方法来限定时间,如果需要跑多个实例,可以使用文件锁的形式来确保;

如果是web形式的话,则可以使用js来配合,像wp里面的cron其实就是这么实现的...

之前在团购平台上实现了一个这样的应用,此处我给出一些代码:

/**

* 任务计划类 taskschedule

*

* 读取指定的 任务配置文件 来执行任务计划

*/

class TaskSchedule {

/**

* 运行时目录,存放 锁定文件 和 日志文件 所在地

*

* @var string

*/

static $rtDir = null;

/**

* 锁定文件标识,确保单台机器内存中只有一个运行实例

*/

const LOCK_PID = 'taskschedule.pid';

private function __construct(){

// 此处可以扩展成 读取配置文件

$this->_tasks = require 'tasks.php';

}

/**

* 返回 TaskSchedule 单例对象

*

* @return TaskSchedule

*/

static function getInstance(){

static $inst = null;

if (!$inst)

$inst = new self();

return $inst;

}

/**

* 运行 任务实例

*/

function dealTask($id){

if (isset($this->_tasks[$id])){

$inst = isset($this->_tasks[$id]['inst']) ? $this->_tasks[$id]['inst'] : null;

if ($inst instanceof TaskBase){

// Only a instance can execute

}else {

$className = $this->_tasks[$id]['class'];

if (!class_exists($className,false)){

require_once $this->_tasks[$id]['file'];

}

if (isset($this->_tasks[$id]['config']))

$inst = new $className($this->_tasks[$id]['config']);

else

$inst = new $className();

$this->_tasks[$id]['inst'] = $inst;

$inst->run();

}

}else {

CoreApp::writeLog("task: {$id} not defined ",'error');

}

}

}

class TaskScheduleException extends Exception {}

abstract class TaskBase {

/**

* 任务标题

*

* @var string

*/

public $title;

/**

* 起始时间

*

* @var int

*/

public $st;

/**

* 结束时间

*

* @var int

*/

public $et;

/**

* 执行任务,由任务制定者实现

*/

abstract function run();

}

调用的时候

ignore_user_abort();

$op = "你定义的标识"

TaskSchedule::getInstance()->dealTask($op);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值