Wednesday, April 16, 2008

Programming Timeout / Retry

Programming timeout or number of retry is needed to make sure your program won't stuck it that part of code. Here's a template of how to do it :

For Java :


long startTime = System.currentTimeMillis();
long elapsedTime;
do {
//Do your job here, but do not loop for input/event
elapsedTime = System.currentTimeMillis() - startTime;
} while ((elapsedTime < TIMEOUT_VALUE) &&
(event != true));

For C/C++ (Under GCC Linux/Cygwin/BSD) :


#include <time.h>
uint32_t startTime = time(NULL);
uint32_t elapsedTime;
do {
//Do your job here, but do not loop for input/event
elapsedTime = difftime(time(NULL), startTime);
} while ((elapsedTime < TIMEOUT_VALUE) &&
(event != true));

For retry counter, just replace the elapsedTime with retryCounter..Something like:


// do {
// result = do_your_work();
// if (result != OK) retryCounter++;
// } while ((retryCounter < MAX_RETRY) && (result != OK))

Notes on Timer Resolution
For C/C++ under GCC, the method's timer resolution is second (usually enough for most of applications, but I'll post again on how to produce microsecond resolution later).

For Java, only Linux side that can give you millisecond resolution. Windows implementation is not that good. I haven't found the patch yet. I'll post again after I find it.

No comments: