Stopping scheduled task and resheduling it

In my program I'm in need of using timeouts in GUI. For instance, the user starts using GUI, the timeout starts couting. When he reaches some stage, the current timeout is being discarded and new is started.

I was thinking about using Timer & TimerTask classes to do it in such manner :

TimerTask1 -> do some stuff (including Timer cancel & purge)

TimerTask2 -> do another stuff (including Timer cancel & purge)

Timer -> one timer for two tasks, since they won't be running parallel.

The code would look like this:

=== user starts using GUI at stage A ===

Timer.shedule(TimerTask1, neededAmountOfTime)

==after reaching stage B==

Timer.cancel()

Timer.purge()

Timer.shedule(TimerTask2, neededAmountOfTime)

==after reaching final stage C==

Timer.cancel()

Timer.purge()

Will it work as I think it should ? At stage A TimerTask1 is scheduled and triggered if user didn't reach stage B within allocated time. If he reaches stage B, Timertask1 is killed and TimerTask2 is scheduled. If user didn't reach stage C within allocated time, TimerTask2 is triggered. If user reaches stage C within allocated time, non of the TimerTasks is triggered.

Am I right with my thinking?

EDIT:

I tried the above method. Ofcourse after canceling Timer I had to create a new one before scheduling to it. The problem is, that sometimes the timer works and sometimes not. Is there any way to check if TimerTask was correctly scheduled on Timer?

链接地址: http://www.djcxy.com/p/74910.html

上一篇: 如何创建可以取消和重新计划的计时器任务

下一篇: 停止计划任务并重新计划它