Embedded Freaks..

September 24, 2007

Programming Timeout / Retry

Filed under: java, programming-tips — Tags: , , — kunilkuda @ 1:19 am

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.

Advertisements

1 Comment »

  1. […] You can also combined the technique with do-while loop (see my previous post). […]

    Pingback by Programming Timeout under FreeRTOS « Embedded Freaks.. — February 19, 2009 @ 11:24 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: