I want to share with you a nice unit that provide a retry pattern. How many times you want to execute some code and, if that method throws an exception, you want to retry executing it several times? For example when you try to connect to a service or network resource or a database. The operation was something that failed frequently enough that it was necessary sometimes to retry until it succeeded. With this unit you enable an application to handle transient failures by transparently retrying a failed operation.
Here is the RetryHelperU:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unit RetryHelperU; | |
interface | |
uses | |
System.SysUtils; | |
type | |
TRetryHelper = class(TObject) | |
class procedure DoRetry(const ATimes: Integer; ADelayInMillis: Int64; | |
AProc: TProc); | |
end; | |
implementation | |
uses | |
System.Classes; | |
{ TRetryer } | |
class procedure TRetryHelper.DoRetry(const ATimes: Integer; | |
ADelayInMillis: Int64; AProc: TProc); | |
var | |
LRetry: Integer; | |
begin | |
LRetry := 0; | |
while true do | |
begin | |
try | |
Inc(LRetry); | |
AProc(); | |
break; | |
except | |
on E: Exception do | |
begin | |
if LRetry = ATimes then | |
raise E; | |
if ADelayInMillis > 0 then | |
TThread.Sleep(ADelayInMillis); | |
end | |
end; | |
end; | |
end; | |
end. |
The snippet is very simple to understand: you have to specify the number of retries, the milliseconds between each retry and a TProc that represents the operation to do.
I also added this project to my Delphi Demos repository.
I hope it will be useful!