首页 > 开发 > PHP > 正文

php workerman定时任务的实现代码

2024-05-04 22:41:40
字体:
来源:转载
供稿:网友

一、下载workerman

https://www.workerman.net/download

二、下载workerman/mysql

http://doc3.workerman.net/640201

1、定时函数为匿名函数(闭包)

use /Workerman/Worker;use /Workerman/Lib/Timer;require_once './Workerman/Autoloader.php';$task = new Worker();// 开启多少个进程运行定时任务,注意多进程并发问题$task->count = 1;$task->onWorkerStart = function($task){  // 每2.5秒执行一次  $time_interval = 2.5;  Timer::add($time_interval, function()  {    echo "task run/n";  });};// 运行workerWorker::runAll();

2、定时函数为普通函数

require_once './Workerman/Autoloader.php';use /Workerman/Worker;use /Workerman/Lib/Timer;// 普通的函数function send_mail($to, $content){  echo "send mail .../n";}$task = new Worker();$task->onWorkerStart = function($task){  $to = 'workerman@workerman.net';  $content = 'hello workerman';  // 10秒后执行发送邮件任务,最后一个参数传递false,表示只运行一次  Timer::add(10, 'send_mail', array($to, $content), false);};// 运行workerWorker::runAll();

3、定时函数为类的方法

require_once './Workerman/Autoloader.php';use /Workerman/Worker;use /Workerman/Lib/Timer;class Mail{  // 注意,回调函数属性必须是public  public function send($to, $content)  {    echo "send mail .../n";  }}$task = new Worker();$task->onWorkerStart = function($task){  // 10秒后发送一次邮件  $mail = new Mail();  $to = 'workerman@workerman.net';  $content = 'hello workerman';  Timer::add(10, array($mail, 'send'), array($to, $content), false);};// 运行workerWorker::runAll();

4、定时函数为类方法(类内部使用定时器)

require_once './Workerman/Autoloader.php';use /Workerman/Worker;use /Workerman/Lib/Timer;class Mail{  // 注意,回调函数属性必须是public  public function send($to, $content)  {    echo "send mail .../n";  }  public function sendLater($to, $content)  {    // 回调的方法属于当前的类,则回调数组第一个元素为$this    Timer::add(10, array($this, 'send'), array($to, $content), false);  }}$task = new Worker();$task->onWorkerStart = function($task){  // 10秒后发送一次邮件  $mail = new Mail();  $to = 'workerman@workerman.net';  $content = 'hello workerman';  $mail->sendLater($to, $content);};// 运行workerWorker::runAll();

5、定时函数为类的静态方法

require_once './Workerman/Autoloader.php';use /Workerman/Worker;use /Workerman/Lib/Timer;class Mail{  // 注意这个是静态方法,回调函数属性也必须是public  public static function send($to, $content)  {    echo "send mail .../n";  }}$task = new Worker();$task->onWorkerStart = function($task){  // 10秒后发送一次邮件  $to = 'workerman@workerman.net';  $content = 'hello workerman';  // 定时调用类的静态方法  Timer::add(10, array('Mail', 'send'), array($to, $content), false);};// 运行workerWorker::runAll();            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表