tomloprod/time-warden

TimeWarden 是一个轻量级的 PHP 库,允许您监控任务和任务组的处理时间(在开发阶段非常有用)。此外,它还允许您为任务设置最大执行时间,当任务超过其计划持续时间时,可以采取主动行动。

v1.2.1 2024-08-11 11:13 UTC

This package is auto-updated.

Last update: 2024-09-11 11:45:32 UTC


README

GitHub Workflow Status (master) Total Downloads Latest Version License

⏱️ 关于 TimeWarden

TimeWarden 是一个轻量级的 PHP 库,允许您 监控任务的执行时间在开发阶段和调试期间非常有用),并让您为任务设置估计的执行时间,当任务超过其估计的持续时间时,可以启用反应性操作

TimeWarden 是框架无关的,这意味着它不属于任何特定的框架。它可以无缝集成到任何 PHP 应用程序中,无论它们是否使用 Laravel(🧡)、Symfony 或根本不使用任何框架。

✨ 入门

反应性操作

您可以指定每个任务的估计执行时间,并在时间超过时执行操作(例如:发送电子邮件、将条目添加到错误日志等)。

示例

timeWarden()->task('Checking articles')->start();

foreach ($articles as $article) {
    // Perform long process... 🕒 
}

// Using traditional anonymous function
timeWarden()->stop(static function (Task $task): void {
    $task->onExceedsMilliseconds(500, static function (Task $task): void {
        // Do what you need, for example, send an email 🙂
        Mail::to('foo@bar.com')->queue(
            new SlowArticleProcess($task)
        );
    });
});

// Or using an arrow function
timeWarden()->stop(static function (Task $task): void {
    $task->onExceedsMilliseconds(500, fn (Task $task) => Log::error($task->name.' has taken too long'));
});

可用方法

如果您对使用 onExceedsMilliseconds 没有信心,您还有其他选择

$task->onExceedsSeconds(10, function () { ... });
$task->onExceedsMinutes(5, function () { ... });
$task->onExceedsHours(2, function () { ... });

执行时间调试

它允许您测量应用程序中任务的执行时间,以及将那些任务添加到组中的可能性。

简单任务

timeWarden()->task('Articles task');

foreach ($articles as $article) {
    // Perform long process...
}

// Previous task is automatically stopped when a new task is created
timeWarden()->task('Customers task');

foreach ($customers as $customer) {
    // Perform long process...
}

/**
 * You can print the results directly or obtain a 
 * summary with the `getSummary()` method
 */
echo timeWarden()->output();

结果

╔═════════════════════ TIMEWARDEN ═════╤═══════════════╗
║ GROUP               │ TASK           │ DURATION (MS) ║
╠═════════════════════╪════════════════╪═══════════════╣
║ default (320.37 ms) │ Articles task  │ 70.23         ║
║                     │ Customers task │ 250.14        ║
╚══════════════════ Total: 320.37 ms ══╧═══════════════╝

分组任务

timeWarden()->group('Articles')->task('Loop of articles')->start();

foreach ($articles as $article) {
    // Perform first operations
}

timeWarden()->task('Other articles process')->start();
Foo::bar();

// Previous task is automatically stopped when a new task is created
timeWarden()->group('Customers')->task('Customers task')->start();

foreach ($customers as $customer) {
    // Perform long process...
}

timeWarden()->task('Other customer process')->start();
Bar::foo();

/**
 * You can print the results directly or obtain a 
 * summary with the `getSummary()` method
 */
echo timeWarden()->output();

结果

╔═══════════════════════╤══ TIMEWARDEN ══════════╤═══════════════╗
║ GROUP                 │ TASK                   │ DURATION (MS) ║
╠═══════════════════════╪════════════════════════╪═══════════════╣
║ Articles (85.46 ms)   │ Loop of articles       │ 70.24         ║
║                       │ Other articles process │ 15.22         ║
╟───────────────────────┼────────────────────────┼───────────────╢
║ Customers (280.46 ms) │ Customers task         │ 250.22        ║
║                       │ Other customer process │ 30.24         ║
╚═══════════════════════ Total: 365.92 ms ═══════╧═══════════════╝

🧙 提示

如果您的应用程序有任何日志系统,那么发送输出的地方将非常完美。

if (app()->environment('local')) {
    Log::debug(timeWarden()->output());
}

使用 TimeWarden 的方法

您可以使用 TimeWarden,使用别名 timeWarden()(或 timewarden()

timeWarden()->task('Task 1')->start();

或直接调用 TimeWarden 门面类的静态方法

TimeWarden::task('Task 1')->start();

您决定如何使用它 :)

🧱 架构

TimeWarden 由几种类型的元素组成。以下是每个元素的某些功能。

TimeWarden

Tomloprod\TimeWarden\Support\Facades\TimeWarden 是一个门面,它作为使用 TimeWarden 其他元素的简化接口。

方法

此类中的大多数方法都返回它们的实例,从而允许通过方法链实现流畅的语法。

// Destroys the TimeWarden instance and returns a new one.
TimeWarden::reset(): TimeWarden

// Creates a new group.
TimeWarden::group(string $groupName): TimeWarden

/**
 * Creates a new task inside the last created group
 * or within the TimeWarden instance itself.
 */
TimeWarden::task(string $taskName): TimeWarden

// Starts the last created task
TimeWarden::start(): TimeWarden

// Stops the last created task
TimeWarden::stop(): TimeWarden

// Obtains all the created groups
TimeWarden::getGroups(): array

/**
 * It allows you to obtain a TimeWardenSummary instance, 
 * which is useful for getting a summary of all groups 
 * and tasks generated by TimeWarden. 
 * 
 * Through that instance, you can retrieve the summary 
 * in array or string (JSON) format.
 */
TimeWarden::getSummary(): TimeWardenSummary;

/**
 * Returns a table with execution time debugging info 
 * (ideal for displaying in the console).
 */
TimeWarden::output(): string

此外,它还具有 Taskable 接口的所有方法。

任务

您创建的所有任务都是 Tomloprod\TimeWarden\Task 的实例。任务最有用的方法和属性如下

属性

  • name

方法

$task = new Task('Task 1');

$task->start(): void
$task->stop(?callable $fn = null): void

// Returns the duration of the task in a human-readable format. Example: *1day 10h 20min 30sec 150ms*
$task->getFriendlyDuration(): string
// Returns the duration of the task in milliseconds
$task->getDuration(): float

// Returns the taskable element to which the task belongs.
$task->getTaskable(): ?Taskable

$task->hasStarted(): bool
$task->hasEnded(): bool

$task->getStartDateTime(): ?DateTimeImmutable
$task->getEndDateTime(): ?DateTimeImmutable

$task->getStartTimestamp(): float
$task->getEndTimestamp(): float

/** @return array<string, mixed> */
$task->toArray(): array

// Reactive execution time methods
$task->onExceedsMilliseconds(float $milliseconds, callable $fn): ?Task
$task->onExceedsSeconds(float $seconds, callable $fn): ?Task
$task->onExceedsMinutes(float $minutes, callable $fn): ?Task
$task->onExceedsHours(float $hours, callable $fn): ?Task

Group

您创建的所有组都是 Tomloprod\TimeWarden\Group 对象的实例。组最有用的方法和属性如下

属性

  • name

方法

// Starts the last created task inside this group
$group->start(): void

此外,它还具有 Taskable 接口的所有方法。

Taskable

Tomloprod\TimeWarden\Contracts\TaskableTimeWarden 实例以及每个任务 所使用的接口。

方法

// Create a new task within the taskable.
$taskable->createTask(string $taskName): Task;

$taskable->getTasks(): array;

$taskable->getLastTask(): ?Task;

// Return the total time in milliseconds of all tasks within the taskable.
$taskable->getDuration(): float;

$taskable->toArray(): array;

$taskable->toJson(): string;

TimeWardenSummary

Tomloprod\TimeWarden\TimeWardenSummary 是一个类,允许获取使用 TimeWarden 生成的组和它们的任务的总体摘要。

它对于获取数组或字符串(JSON)格式的摘要非常有用。

您可以如下获取 TimeWardenSummary 的实例

/** @var Tomloprod\TimeWarden\TimeWardenSummary $timeWardenSummary */
$timeWardenSummary = timeWarden()->getSummary();

方法

$timeWardenSummary->toArray(): array;
$timeWardenSummary->toJson(): string;

以下是返回数组格式的数据示例

$summaryArray = [
    [
        'name' => 'default',
        'duration' => 42.0,
        'tasks' => [
            [
                'name' => 'TaskName1',
                'duration' => 19.0,
                'friendly_duration' => '19ms',
                'start_timestamp' => 1496664000.0,
                'end_timestamp' => 1496664000.019,
                'start_datetime' => '2017-06-05T12:00:00+00:00',
                'end_datetime' => '2017-06-05T12:00:00+00:00',
            ],
            [
                'name' => 'TaskName2',
                'duration' => 23.0,
                'friendly_duration' => '23ms',
                'start_timestamp' => 1496664000.0,
                'end_timestamp' => 1496664000.023,
                'start_datetime' => '2017-06-05T12:00:00+00:00',
                'end_datetime' => '2017-06-05T12:00:00+00:00',
            ],
        ],
    ],
    [ // Others groups... ],
];

🚀 安装与需求

需要 PHP 8.2+

您可以使用 Composer 将 TimeWarden 安装到您的 PHP 项目中

composer require tomloprod/time-warden

🧑‍🤝‍🧑 贡献

欢迎贡献,可通过拉取请求进行提交。在提交任何拉取请求之前,请查看这些指南

TimeWardenTomás López 创建,并在 MIT 许可证 下开源。