Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The easiest approach would be to use a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html" rel="nofollow"><code>Timer</code></a>. With that, you don't need the <code>if</code> logic; you can just use the <code>firstTime</code> argument when scheduling a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html" rel="nofollow"><code>TimerTask</code></a>.</p> <pre><code>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); </code></pre> <p>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:</p> <pre><code>timer.schedule(task, threshold); </code></pre> <p>If you're using Swing, you should use a Swing <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html" rel="nofollow">Timer</a> rather than a java.util.Timer. See <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html" rel="nofollow">How to Use Swing Timers</a> for more info.</p> <p>EDIT: Your comment clarified things a bit. It's fairly easy to do what you described:</p> <pre><code>Timer timer = new Timer(); TimerTask task = new TimerTask() { private final long start = System.currentTimeMillis(); @Override public void run() { if (System.currentTimeMillis() - start &lt; 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); </code></pre> <p>Note that "do something" and "do something else" can be method calls to an enclosing class.</p> <p>A cleaner approach might be to define several <code>TimerTask</code>s 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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload