0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#】特定の時間の間、成功するまで同じ処理を続ける方法

Posted at

概要

特定の時間の間、成功するまで同じ処理を続ける処理のサンプルコードを記載しました。

コード

一時間の間だけ、成功するまで同じ処理を繰り返すサンプルコードです。

using System;
using System.Diagnostics;
using System.Threading;

public bool Sample()
{
    const int MaxRetryTime = 1000 * 60 * 60;
    var sw = new Stopwatch();
    sw.Start();
    while (sw.ElapsedMilliseconds < MaxRetryTime)
    {
        try
        {
            // 成功するまで続けたい処理を記載

            // 成功した場合
            return true;
        }
        catch (Exception ex)
        {
            // 失敗した場合
            
            // エラー処理 (ログ出力等)
        }

        // 失敗した場合は10秒待機して再スタート
        Thread.Sleep(1000 * 10);
    }

    // 成功しなかった場合
    return false;
}

const int MaxRetryTime = 1000 * 60 * 60;

  • この変数はtryの中含めてプログラム実行中は絶対に変更されるべきではない値なのでconstを使用しています。
  • 1000 * 60 * 60は、時間を定義しています。ミリ秒単位で定義するので、「1000ミリ秒 = 1秒」 として最初に1000を記載しています。

StopwatchクラスのElapsedMilliseconds

  • こちらはストップウォッチが開始されてから (Start()が呼ばれてから) の経過時間をミリ秒単位で返すプロパティです。

Thread.Sleep(1000 * 10);

  • 処理が失敗したらすぐに再実行するのではなく、10秒間待ってから再度処理を実行するための処理です。

終わりに

データベースにアクセスして操作する場合や外部サービスと通信する場合等に使用できるかもと思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?