You state:
The problem is what you just mentioned about the timer, i want to stop the current tasks that are running
As per the java.util.Timer
API, calling cancel()
on the Timer object stops it from creating new future tasks, but does not stop the currently running tasks. So since this is your problem, it's no surprise that cancel()
does not help you.
The solution? That lies in the TimerTasks that you're creating. If this were my code, I'd create a class that extends TimerTask, that has a clean way of stopping it, perhaps give it a cancel()
method, keep a collection of active running instances of these, and then call cancel()
when desired.
A caveat, it can be dangerous to use java.util.Timer
in Swing applications without care. If your tasks involve making Swing calls, you will need to take care to make your Swing calls on the Swing event thread. If not, and if all the tasks do are database actions, then you're OK.
As an aside, if you use a ScheduledExecutorService, you can fill it with either Runnables or Callables. The schedule(...)
or scheduleAtFixedRate(...)
method returns a ScheduledFuture that you can call cancel()
on. I think that this works by calling Thread.interrupt()
on the task. And so if you go this route, your task should be interruptable and should be able to smoothly handle InterruptedException
.