0

I have a glitch in my program where it takes way too long to execute a line of code,

So i thought of adding a timer to keep track of how long it takes to execute that line,

And if it takes > 5.5 seconds, re-execute the line.

But here's the problem,

How can i make it so that the timer is executing at the same time the line of code is executing?

I tried this:

        long start = System.currentTimeMillis();

    //condition

    Thread.sleep(5000);

    long elapsedTime = System.currentTimeMillis() - start;
    System.out.println(elapsedTime);

    if(elapsedTime > 5500) {
        System.out.println("things are taking too long");

        //re-execute condition
    }

Lets pretend the condition did take more than 5.5 seconds. My program wouldn't know the value of elapsedTime until after the condition executes, and I need to be able to have the value of elapsedTime at the same time the condition is executing so that if at any time the condition takes longer than 5.5 seconds, the program re-executes that line. Is that possible?

dam1ne
  • 181
  • 1
  • 2
  • 17
  • Yes, that is possible. [Why is “Is it possible to…” a poorly worded question?](https://softwareengineering.meta.stackexchange.com/q/7273/202153) – Andreas Jan 01 '20 at 03:40
  • See answer to [How do I schedule a task to run once?](https://stackoverflow.com/a/34324083/5221149) for how to schedule a task to run 5 seconds later. When your condition ends, call `cancel()` so the scheduled task won't run (unless it already did). The `cancel()` method is mentioned at the end of the answer. – Andreas Jan 01 '20 at 03:43

0 Answers0