Java: Keep executing if statement

user760220

I have an if statement which evaluates the time since the program has begun running and if the time is above a certain threshold, does something. I want this if statement to be checked throughout the whole time the program is running while at the same time have the program continue execution. How would I go about doing this?

Thank you.

Ted Hopp

The easiest approach would be to use a Timer. With that, you don't need the if logic; you can just use the firstTime argument when scheduling a TimerTask.

Timer timer = new Timer();
TimerTask task = new TimerTask() {
    @Override
    public void run() {
        // do something
    }
};
// schedule the task to be run every 100ms (0.1 sec),
// starting after "threshold" milliseconds have past
timer.schedule(task, threshold, 100);

It's not clear from your description if you want to repeatedly "do something" once the time threshold has been exceeded, or if you just want to wait until a certain time has passed and then "do something" once. The above code is for the repeating case. For a one-shot occurrence at some future time, change the last line to:

timer.schedule(task, threshold);

If you're using Swing, you should use a Swing Timer rather than a java.util.Timer. See How to Use Swing Timers for more info.

EDIT: Your comment clarified things a bit. It's fairly easy to do what you described:

Timer timer = new Timer();
TimerTask task = new TimerTask() {
    private final long start = System.currentTimeMillis();
    @Override
    public void run() {
        if (System.currentTimeMillis() - start < threshold) {
            // do something
        } else {
            // do something else
        }
    }
};
// schedule the task to be run every 100ms (0.1 sec), starting immediately
timer.schedule(task, 0, 100);

Note that "do something" and "do something else" can be method calls to an enclosing class.

A cleaner approach might be to define several TimerTasks that are scheduled to execute at different times. The "something else" task that triggers an exception can be scheduled for one-time execution at the threshold time. You can also cancel individual tasks and you can even schedule a task that will cancel another task.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Error executing sql statement when using java expression in ireport

분류에서Dev

Recursive function with local variable not executing if statement

분류에서Dev

Executing one jquery statement after css change is complete

분류에서Dev

Error while executing linux command using Java

분류에서Dev

Executing Bash Script Returns Null In Java

분류에서Dev

Java Error: "; Expected Not a statement "

분류에서Dev

an issue on "if statement" in Java

분류에서Dev

Java:Unreachable statement error

분류에서Dev

Java Switch statement confusion

분류에서Dev

Error while executing statement in ASP.NET MVC4 LINQ

분류에서Dev

if Statement not evaluating boolean correctly in Java?

분류에서Dev

"Missing return statement" error in Java

분류에서Dev

when executing program, extra input command causes logical errors java

분류에서Dev

Java : A pipe used in a print statement in java?

분류에서Dev

How to keep a Java program secure from hacking

분류에서Dev

return statement not returning control to caller in java

분류에서Dev

java Android - how can I keep Image's actual size?

분류에서Dev

I keep on getting the error "java.util.InputMismatchException" in my code

분류에서Dev

Java Swing: How to keep parent window open after closing JFileChooser

분류에서Dev

how to keep 10 biggest integer while reading a list in java?

분류에서Dev

Android: How to solve java.lang.RuntimeException error occured while executing doInBackground()?

분류에서Dev

PHP not executing

분류에서Dev

Java- why is if() block inside of while() statement executed?

분류에서Dev

Row_number() and partition by statement of sql is not working in java class

분류에서Dev

Datastax Cassandra Java 드라이버 RetryPolicy for Statement with paging

분류에서Dev

I am trying to write a program that will keep track of a players wins everything works except can anyone tell me why my if statement wont work?

분류에서Dev

java.sql.Statement에서 DataBaseConnection.Statement로 변환 할 수 없습니다.

분류에서Dev

How to keep cmd from exiting using Java 'Runtime.getRuntime().exec' command

분류에서Dev

How to keep java.awt.List from covering javax.swing.JMenu

Related 관련 기사

  1. 1

    Error executing sql statement when using java expression in ireport

  2. 2

    Recursive function with local variable not executing if statement

  3. 3

    Executing one jquery statement after css change is complete

  4. 4

    Error while executing linux command using Java

  5. 5

    Executing Bash Script Returns Null In Java

  6. 6

    Java Error: "; Expected Not a statement "

  7. 7

    an issue on "if statement" in Java

  8. 8

    Java:Unreachable statement error

  9. 9

    Java Switch statement confusion

  10. 10

    Error while executing statement in ASP.NET MVC4 LINQ

  11. 11

    if Statement not evaluating boolean correctly in Java?

  12. 12

    "Missing return statement" error in Java

  13. 13

    when executing program, extra input command causes logical errors java

  14. 14

    Java : A pipe used in a print statement in java?

  15. 15

    How to keep a Java program secure from hacking

  16. 16

    return statement not returning control to caller in java

  17. 17

    java Android - how can I keep Image's actual size?

  18. 18

    I keep on getting the error "java.util.InputMismatchException" in my code

  19. 19

    Java Swing: How to keep parent window open after closing JFileChooser

  20. 20

    how to keep 10 biggest integer while reading a list in java?

  21. 21

    Android: How to solve java.lang.RuntimeException error occured while executing doInBackground()?

  22. 22

    PHP not executing

  23. 23

    Java- why is if() block inside of while() statement executed?

  24. 24

    Row_number() and partition by statement of sql is not working in java class

  25. 25

    Datastax Cassandra Java 드라이버 RetryPolicy for Statement with paging

  26. 26

    I am trying to write a program that will keep track of a players wins everything works except can anyone tell me why my if statement wont work?

  27. 27

    java.sql.Statement에서 DataBaseConnection.Statement로 변환 할 수 없습니다.

  28. 28

    How to keep cmd from exiting using Java 'Runtime.getRuntime().exec' command

  29. 29

    How to keep java.awt.List from covering javax.swing.JMenu

뜨겁다태그

보관