在我们项目中经常会遇到需要定时器的功能来解决一些定时任务,比如统计订单,定时消息,通知等等,但是PHP没有给我们提供类型定时器的功能,总不能用Linux带的cron来实现把,那么用什么方式可以简单实现呢?
1.Laravel或Lumen的提供的定时器功能
这个方法仅仅在Linux下有效
ssh root@you_server_ip
crontab –e
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
<?php
/*
*author:mjshu
*time 2016/3/29 下午4:20
*All rights reserved
*/
namespace App\Console;
use Illuminate\Support\Facades\DB;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* 应用提供的Artisan命令
*
* @var array
*/
protected $commands = [
//
];
/**
* 定义应用的命令调度
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
* @translator laravelacademy.org
*/
protected function schedule(Schedule $schedule)
{
/** 每分钟检查一次CDN状态 */
$schedule->call('App\Http\Controllers\Admin\Work\CdnController@WorkCdn')->everyMinute();
/**
* 每日更新cdn
*/
$schedule->call('App\Http\Controllers\Admin\QiNiu\QiNiuController@fileUpdateUrl')->hourly();
/**
* 检查Redis的默认方案与自学习方案时候存在
*/
$schedule->call('App\Http\Controllers\Admin\Work\SchemeController@schemeWork')->everyMinute();
/**
* 检查渠道在redis是否正常
*/
$schedule->call('App\Http\Controllers\Admin\Work\DitchController@exists')->everyMinute();
/**
* 每日将redis数据写入DB
*/
$schedule->call('App\Http\Controllers\Admin\Work\DataDbLogController@redis6')->dailyAt('23:55');
$schedule->call('App\Http\Controllers\Admin\Work\DataDbLogController@brandTotal')->dailyAt('23:55');
$schedule->call('App\Http\Controllers\Admin\Work\DataDbLogController@versionTotal')->dailyAt('23:55');
}
}
}
2.WorkerMan提供的定时器功能
优点,任务常驻内存
$worker = new BusinessWorker();
$worker->eventHandler = 'App\Http\Controllers\WebSocket\WebSocketController';
$worker->name = 'BusinessWorker';
$worker->count = 3; //每个进程都可以单独的运行定时器 定时器进程从0到2
$worker->registerAddress = '127.0.0.1:1238';
<?php
/*
*author:mjshu
*time 2017/9/29 下午4:20
*All rights reserved
*/
namespace App\Http\Controllers\WebSocket;
use App\Http\Controllers\Chat\ChatController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Group\GroupController;
use App\Http\Controllers\User\UserController;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Workerman\Lib\Timer;
class WebSocketController extends Controller
{
public static function onWorkerStart($worker){
//定时任务,参数1,秒数 参数2,执行的任务
Timer::add(10,function(){
echo 123;
});
}
如果我们需要第一个进程执行A任务 第二个进程执行B任务那么可以这样写
public static function onWorkerStart($worker){
if($worker->id === 0){
Timer::add(10,function(){
echo 123;
});
}
if($worker->id === 1){
Timer::add(10,function(){
echo 223;
});
}
}
执行任务如下
WechatIMG393.jpeg当然如果你需要在Linux运行推荐使用supervisor进行进程的守护
网友评论