phillipsdata / priority-schedule
一个优先级调度库
1.0.2
2016-03-24 21:56 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: ^4.8
- satooshi/php-coveralls: ^1.0
- squizlabs/php_codesniffer: ^2.2
This package is auto-updated.
Last update: 2024-09-23 09:41:28 UTC
README
这是一个优先级调度库。
该库提供数据结构以执行 轮询 和 第一个可用 的项目访问。
安装
composer require phillipsdata/priority-schedule
用法
有两个内置的优先级调度
- 轮询
- 返回具有最小权重且每个项目的权重成比例的项目。
- 第一个可用
- 返回添加的顺序中的项目(先进先出),并且只返回有效的项目。
轮询
轮询调度允许您通过指定定义返回项目优先级的比较器以均匀分布的方式检索项目。
假设您有3个桶对象
假设每次我们检索一个桶时,我们增加其计数,然后将其添加回调度,我们期望按照以下顺序检索桶
A, A, A, B, B, A, A, C, B
use PhillipsData\PrioritySchedule\RoundRobin; // Create our buckets $a = new stdClass(); $a->name = 'A'; $a->count = 0; $b = new stdClass(); $b->name = 'B'; $b->count = 2; $c = new stdClass(); $c->name = 'C'; $c->count = 4; // Initialize the priority schedule with a custom comparator $rr = new RoundRobin(); $rr->setCallback(function ($x, $y) { if ($x->count === $y->count) { return 0; } // we want low items first so they have higher (1) priority return $x->count < $y->count ? 1 : -1; }); // Add items to the schedule $rr->insert($a); $rr->insert($b); $rr->insert($c); // Fetch items foreach ($rr as $item) { echo $item->name . " (" . ++$item->count . ")\n"; if ($item->count < 5) { $rr->insert($item); } }
输出
A (1)
A (2)
A (3)
B (3)
B (4)
A (4)
A (5)
C (5)
B (5)
第一个可用
第一个可用的调度允许您使用回调跳过无效元素,按照添加的顺序检索元素(先进先出)。
假设您有3个桶对象
假设每次我们检索一个桶时,我们减少其计数,然后将其添加回调度,我们期望按照以下顺序检索桶
B, C, B, C, C, C
这是因为一旦桶达到 0
,我们不再将其视为有效。
use PhillipsData\PrioritySchedule\FirstAvailable; // Create our buckets $a = new stdClass(); $a->name = 'A'; $a->count = 0; $b = new stdClass(); $b->name = 'B'; $b->count = 2; $c = new stdClass(); $c->name = 'C'; $c->count = 4; // Initialize the priority schedule with a custom filter $fa = new FirstAvailable(); $fa->setCallback(function ($item) { return $item->count > 0; }); // Add items to the schedule $fa->insert($a); $fa->insert($b); $fa->insert($c); foreach ($fa as $item) { echo $item->name . " (" . --$item->count . ")\n"; if ($item->count > 0) { $fa->insert($item); } }
输出
B (1)
C (3)
B (0)
C (2)
C (1)
C (0)