alancole / atomic
本包最新版本(1.0.1)没有提供许可证信息。
PHP事件/调度库。
1.0.1
2017-03-22 15:09 UTC
Requires
- g4/cron: ^0.1.2
This package is auto-updated.
Last update: 2024-09-24 04:44:04 UTC
README
Atomic
Atomic是一个PHP调度库,可以构建和安排事件。您可以使用Atomic来简单地安排事件,或者您可以将适配器附加到它并使用我们提供的bin来根据cron计划运行任务。
安排任务
# Schedule an event on the first of december each year. $yearly = new Atomic\Schedule\Yearly(new DateTime("1st December")); $event = new Atomic\Event("dec-log-clear", $yearly, function() { Logs::clearAll(); // hypothetical event code. }); # Some check at a later time if ($event->isDue()) { $event->fire(); }
堆栈
如果您喜欢,可以将所有事件注册到一个堆栈中,并且堆栈会在事件到期时触发它们。
$stack = new Atomic\Event\Stack([$event, $event2, $event3]); $evnt = $stack->getNextEvent(); if ($evnt) { Log::info("Triggering event " . $evnt->getName()); $result = $evnt->fire(); Log::info("Event Return: " . $result); }
如果您不需要关心除了返回值之外的其他事件数据,只需要求堆栈为您触发事件即可,如果找到事件,它将运行它;如果没有,它将返回false。
$return = $stack->trigger(); if ($return) { Log::info("Oh, we fired an event. It returned: " . $return); } else { Log::info("No events found."); }
映射器
我们提供了一个简单的映射器,它将事件数组转换为堆栈。如果您在数据库表中存储事件并希望将其加载到堆栈中,这非常有用。
try { $mapper = new Atomic\Event\Mapper($events, [ 'name' => 'name', 'schedule' => 'schedule', 'callback' => 'callback', 'first_run' => 'start_time' ]); $stack = $mapper->getStack(); $stack->trigger(); } catch (Exception $e) { Log::warn($e->getMessage()); }
自定义计划
您可以通过使用ScheduleInterface
来非常简单地添加自己的计划。您的计划必须在构造时接受一个日期时间,并且必须在isNow
上返回true或false。如果此函数返回true,则堆栈将触发此事件。
此类将每星期三触发您的函数。
namespace Custom\Schedule; class EveryWednesday implements \Atomic\Schedule\ScheduleInterface { public function __construct(DateTime $time = null) { return true; } public function getName() { return "Every Wednesday"; } public function getNextRun() { return new DateTime("Wednesday"); } public function getFirstRun() { return new DateTime("Wednesday"); } public function isNow(DateTime $time = null) { return date("D") == "Wed"; } }
安装
composer require waxim/atomic
测试
phpunit