views:

59

answers:

1

I'm calling this tasks:

TimerTask taskA = new ThreadA(this);
TimerTask taskB = new ThreadB(this);

tasks.add(taskA);
tasks.add(taskB);

timer.schedule(taskA, 10000);
timer.schedule(taskB, 5000);

And here are the two TimerTasks:

public class ThreadA extends TimerTask {

    private Ghost ghost;

    public GhostThread(Ghost ghost) {
        this.ghost = ghost;
    }

    @Override
    public void run() {
        ghost.stopBeingDeadAndBeAwesomeAgain();
    }
}

public class ThreadB extends TimerTask {

    private Ghost ghost;

    public WarnThread(Ghost ghost) {
        this.ghost = ghost;
    }

    @Override
    public void run() {
       ghost.beDeadAgain();
    }

}

As you can see, I just call a method after 5 resp. 10 seconds. From time to time I would like to pause the "countdown". This means i want that the time until the 5 seconds are passed isn't running anymore. And then in a later point in time, I would like to resume it.

How can I achieve that??

+1  A: 

The simplest solution would be to simply make a copy of the TimerTask, cancel it to pause, purge if you want, and then reschedule it to resume.

// pause
long timeLeft = 5000 - (new Date().getTime() - taskB.scheduledExecutionTime());
ThreadB taskBpaused = taskB.clone();
taskB.cancel();
timer.purge();
taskB = taskBpaused;

// resume
timer.schedule(taskB, timeLeft, ...);

Important note: if the task hasn't run yet, then this won't work. Google's documentation states that if it hasn't run, scheduledExecutionTime() will return an undefined value, and I don't have the capability to test what exactly that means at the moment. Needless to say, if you aren't sure it's already run, you'll need some kind of conditional to make sure the value isn't undefined.

macamatic
Yes, but the problem is, if my task already runned for let's 3 seconds, then I don't want to run it for 5 seconds again but for 2.
Roflcoptr
Simple enough. You can use the TimerTask's scheduledExecutionTime() method to determine how much time was left before the next execution. I'll edit my post to add this.
macamatic
thanks I'll try it
Roflcoptr
Actually, I cant call clone() ond ThreadB object
Roflcoptr
And the other problem: scheduledExecutionTime() always returns 0....
Roflcoptr