Note that there are some explanatory texts on larger screens.

plurals
  1. POPausing/stopping and starting/resuming Java TimerTask continuously?
    text
    copied!<p>I have one simple question regarding Java TimerTask. How do I pause/resume two TimerTask tasks based on a certain condition? For example I have two timers that run between each other. When a certain condition has been met inside the task of first timer, the first timer stops and starts the second timer, and the same thing happens when a certain condition has been met inside the task of second timer. The class below shows exactly what I mean:</p> <pre><code>public class TimerTest { Timer timer1; Timer timer2; volatile boolean a = false; public TimerTest() { timer1 = new Timer(); timer2 = new Timer(); } public void runStart() { timer1.scheduleAtFixedRate(new Task1(), 0, 1000); } class Task1 extends TimerTask { public void run() { System.out.println("Checking a"); a = SomeClass.getSomeStaticValue(); if (a) { // Pause/stop timer1, start/resume timer2 for 5 seconds timer2.schedule(new Task2(), 5000); } } } class Task2 extends TimerTask{ public void run() { System.out.println("Checking a"); a = SomeClass.getSomeStaticValue(); if (!a) { // Pause/stop timer2, back to timer1 timer1.scheduleAtFixedRate(new Task1(), 0, 1000); } // Do something... } } public static void main(String args[]) { TimerTest tt = new TimerTest(); tt.runStart(); } } </code></pre> <p>So my question is, how do I pause <code>timer1</code> while running <code>timer2</code> and vice versa while <code>timer2</code> is running? Performance and timing is my main concern as this needs to be implemented inside another running thread. By the way I am trying to implement these concurrent timers on Android. </p> <p>Thanks for your help!</p>
 

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