Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Commit

Permalink
feat(Timer): Add Timer Example
Browse files Browse the repository at this point in the history
  • Loading branch information
Rhilip committed Mar 17, 2019
1 parent 3fd6821 commit 4413b46
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 1 deletion.
10 changes: 10 additions & 0 deletions apps/config/http_base.php
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,16 @@
],
],

// 定时器配置
'timer' => [
'crontab' => [
'class' => \apps\task\CronTabTimer::class,
'type' => \Rid\Base\Timer::TICK,
'msec' => 1 * 1000, // 单位为毫秒
'callback' => 'init'
]
],

// 类库配置
'libraries' => [
'swiftmailer' => [
Expand Down
19 changes: 19 additions & 0 deletions apps/task/CronTabTimer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
/**
* Created by PhpStorm.
* User: Rhilip
* Date: 2019/3/17
* Time: 22:19
*/

namespace apps\task;

use Rid\Base\Timer;

class CronTabTimer extends Timer
{
public function init()
{

}
}
14 changes: 14 additions & 0 deletions framework/Base/Timer.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
class Timer implements StaticInstanceInterface
{
use StaticInstanceTrait;

const AFTER = 'after';
const TICK = 'tick';

/**
* 定时器ID
* @var int
Expand Down Expand Up @@ -84,4 +88,14 @@ public function clear()
}
return false;
}

public function run($config)
{
$type = $config['type'];
$msec = $config['msec'];
$callback = $config['callback'];

println('New Timer '. self::class .' added. (Type: ' . $type . ', msec: ' . $msec . ', callback function: ' . $callback . ')');
$this->{$type}($msec, [$this, $callback]);
}
}
11 changes: 11 additions & 0 deletions framework/Http/HttpServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Rid\Base\BaseObject;

use Rid\Base\TaskInterface;
use Rid\Base\Timer;
use Rid\Exceptions\TaskException;
use Rid\Helpers\ProcessHelper;

Expand Down Expand Up @@ -108,6 +109,16 @@ protected function onWorkerStart()
$app->setServ($this->_server);
$app->setWorker($workerId);
$app->loadAllComponents();

if ($workerId == 0) { // 将系统设置中的 Timer 添加到 worker #0 中
foreach (app()->env('timer') as $timer_name => $timer_config) {
$timer_class = $timer_config['class'];
$timer = new $timer_class();
if ($timer instanceof \Rid\Base\TimerInterface) {
$timer->run($timer_config);
}
}
}
});
}

Expand Down
2 changes: 1 addition & 1 deletion framework/Rid.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class Rid
{

// 版本号
const VERSION = 'v0.1.2-alpha';
const VERSION = 'v0.1.3-alpha';

// App实例
protected static $_app;
Expand Down

0 comments on commit 4413b46

Please sign in to comment.