divineomega/attempt

尝试运行一个函数,如果需要则重试

v1.0.1 2020-01-04 22:47 UTC

This package is auto-updated.

Last update: 2024-09-05 08:19:29 UTC


README

此PHP包允许您尝试运行一个函数,如果发生异常则会自动重试。

它可能用于

  • 不可靠的连接或API
  • 与速率限制系统的交互
  • 处理不可靠的输入数据

安装

要安装Attempt,只需运行以下命令。

composer require divineomega/attempt

用法

请参阅以下用法示例。

// Attempts to run the function immediately. If an exception occurs, retry forever.
attempt(function() {
    // ...
})->now();

// Attempts to run the function immediately. If an exception occurs, retry up to 5 times.
attempt(function() {
    // ...
})->maxAttempts(5)
  ->now();

// Attempts to run the function immediately. If an exception occurs, retry until the specified date time.
attempt(function() {
    // ...
})->until($datetime)
  ->now();

// Attempts to run the function immediately. If an exception occurs, retry forever, with a 20 second gap between attempts.
attempt(function() {
    // ...
})->withGap(20)
  ->now();

// Attempts to run the function at a specified date time. If an exception occurs, retry forever. The thread will block until the specified date time is reached.
attempt(function() {
    // ...
})->at($datetime);

这些方法中的大多数可以串联使用,正如您所期望的,以实现所需的功能。