zarganwar/failure-retry-executor

本包最新版本(0.1.4)无可用许可信息。

重试失败的操作

0.1.4 2024-01-05 15:50 UTC

This package is auto-updated.

Last update: 2024-09-05 17:24:12 UTC


README

使用说明

只需运行函数 Zarganwar\FailureRetryExecutor\FailureRetryExecutor::execute(),将您的命令作为第一个参数传递

Zarganwar\FailureRetryExecutor\FailureRetryExecutor::execute(fn() => someFunction());

您的函数将被执行,如果失败(抛出异常或返回false),它将被再次执行。默认最大重试次数为3。当然,您可以通过传递 maxAttempts: int 参数来更改它。

Zarganwar\FailureRetryExecutor\FailureRetryExecutor::execute(
    command: fn() => someFunction(),
    maxAttempts: 99,
);

您还可以通过传递 onSuccess: callable 或/和 onFailure: callable 参数来响应命令结果或失败。

Zarganwar\FailureRetryExecutor\FailureRetryExecutor::execute(
    command: fn() => someFunction(),
    onSuccess: fn($result /* Your callable command result */) => doSomething($result),
    onFailure: fn(Throwable $throwable) => log($throwable),
);

使用示例

// Some HTTP client
$client = new Client();
$logger = new Logger();

Zarganwar\FailureRetryExecutor\FailureRetryExecutor::execute(
    command: fn() => $client->get('https://example.com'),
    onSuccess: function(ResponseInterface $response): void 
    {       
        if ($response->getStatusCode() !== 200) {
            throw new Exception("Server responded with status code {$response->getStatusCode()} instead of 200");
        }
    },
    onFailure: fn(Throwable $throwable) => $logger->log($throwable),
    maxAttempts: 5,
);