23
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

リトライ処理の実装方法いろいろ

Last updated at Posted at 2016-02-01

動作テストはしてないので間違ってるかも

<要件定義>

  • 引数でリトライ回数、リトライ時のスリープ時間をミリ秒で指定(最大実行回数は、最初の1回+リトライ回数)
  • 失敗したら指定された時間待ってから再度実行
  • 処理の結果をreturnで返す。

再起呼び出し

function fn_retry($retry_count=3, $retry_wait_ms=100)
{
    $result = false;

    // ここで処理をして、成否を $resultに入れる。

    if (! $result && $retry_count > 0) {
        usleep($retry_wait_ms * 1000);
        $result = fn_retry($retry_count-1);
    }

    return $result;
}

ループ(while)

function fn_retry($retry_count=3, $retry_wait_ms=100)
{
    $result = false;

    while (true) {

        // ここで処理をして、成否を $resultに入れる。

        if (! $result && $retry_count > 0) {
            usleep($retry_wait_ms * 1000);
            $retry_count--;
        } else {
            break;
        }
    }

    return $result;
}

ループ(for)

function fn_retry($retry_count=3, $retry_wait_ms=100)
{
    $result = false;

    for ( ; $retry_count >= 0; $retry_count-- ) {

        // ここで処理をして、成否を $resultに入れる。

        if ($result) {
        	break;
        }

        usleep($retry_wait_ms * 1000);
    }

    return $result;
}

汎用コールバック

<?php
retry_user_func('get_stdin', ['Yes', 'y']);

/**
 * 指定したコールバック関数をコールし、失敗したらリトライする
 * 
 * @param $callback      コールする callable
 * @param $param_arr     コールバック関数に渡すパラメータを指定する配列
 * @param $retry_count   最大リトライ回数
 * @param $retry_wait_ms リトライ前に入れるスリープ時間(ミリ秒)
 * @return コールバック関数の結果、あるいはエラー時に FALSE を返します。
 */
function retry_user_func(callable $callback, array $param_arr=[], $retry_count=3, $retry_wait_ms=100)
{
	$result = false;

	while (true) {

		try {
			$result = call_user_func_array ($callback, $param_arr);
		}
		catch (Exception $e) {
			$result = false;
		}

		if (! $result && $retry_count > 0) {
			usleep($retry_wait_ms * 1000);
			$retry_count--;
		} else {
			break;
		}
	}

	return $result;
}

/**
 * 指定した文字が入力されたら true を返す
 */
function get_stdin($str1, $str2)
{
	$intpu_list = [$str1, $str2];

	echo "Please input [" . implode('/', $intpu_list) . ']: ';

	$stdin = trim(fgets(STDIN));
	$check = in_array($stdin, $intpu_list);

	echo "You input [".$stdin."], result = " . ($check?'OK':'NG') . "\n";

	return $check;
}
23
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?