-2

Possible Duplicate:
How to timeout a thread
stop a thread in java after a given time - doesn't work

(some kind of thread)that can monitor time taken by a particular task, so that if time reaches to a particular limit, it retries it

Community
  • 1
  • 1

3 Answers3

1

Try it this way....

1. Use CountDownLatch from java.util.concurrent.

2. CountDownLatch cdt = new CountDownLatch(10);

This will do your 10 task and everytime a task is done the count goes down by 1. Use countDown() method to decrement the count when a task is done. Use await() method to allow the execution of flow after 10 tasks are done.

3. Run another thread which monitors the time taken by CountDownLatch to complete the tasks.

4. Suppose the time is exceeding your desired time, then Re-initialize the CountDownLatch

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
0

If you only need a very rough estimate you could create a thread, put it to sleep for however long you need to, and then check if you need to restart your task. For example, you could create a thread whose run() command has a body like this:

Thread.sleep(5000); //5 seconds
while ( needToRestart() )
{
  restart();
  Thread.sleep(5000);
}

This will check if your task needs to be restarted every 5 seconds, and so if necessary. It's important to note that Thread.sleep is not accurate for timing purposes, but this is a cheap solution if the exact amount of time is not important.

bchurchill
  • 1,410
  • 8
  • 23
  • let us say, there is a job and that job creates 10 tasks.Now the problem is to monitor those 10 tasks and see if any task has stuck i.e if a particular task takes >=2 hours, then cancel it and retry it.Provide a sample code in java that does the above thing. – user1610945 Aug 20 '12 at 05:57
  • Guess what? The above will do that. Just combine what Vamsi Mohan Jayanti said with the above code and monitor the difference between the start time and current time inside the thread's loop. When appropriate, you can poll each of your ten tasks. The purpose of stackoverflow isn't for us to write code for you, just to get you through bottlenecks. Let us know if you have specific questions about our answers. – bchurchill Aug 20 '12 at 06:20
  • Although, at this point, java.util.Timer will work better for such a long task. – bchurchill Aug 20 '12 at 06:20
0

If you define a starttime property for your task. You can always start a thread and in the run() method it will monitor your task. In the sense it will measure the currentTime - startTime(available with task object) and check if the difference has reached the threshhold.

  • let us say, there is a job and that job creates 10 tasks.Now the problem is to monitor those 10 tasks and see if any task has stuck i.e if a particular task takes >=2 hours, then cancel it and retry it.Provide a sample code in java that does the above thing. – user1610945 Aug 20 '12 at 05:57