15

Why is there no isCancelled method for a java.util.Timer object?

I would like to schedule a task if the Timer has not been cancelled, and run it directly (on the same thread) if it has been cancelled.

Is the only option to catch the IllegalStateException that might occur if the Timer already has been cancelled? (It feels wrong to catch an IllegalStateException).

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108

2 Answers2

17

How sure are you that you want to use Timer? Use ExecutorService instead, which has isShutdown and has a slew of other benefits to boot. A general recommendation as of Java 5 has been to replace Timers with ExecutorServices.

There's a ScheduledExecutorService interface specifically for scheduled executor services. Instantiate using one of the Executors.new... methods.

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • 1
    Does this mean that the `Timer` class is more or less deprecated? – Simon Forsberg Dec 14 '12 at 14:20
  • 5
    Yes, you could say that. If it fits your bill, use it, but if not, move over to `ExecutorService` and never look back. On second thought, even that advice is dangerous: if you start with `Timer` and your project grows, you may regret not having started out with `ExecutorService`. – Marko Topolnik Dec 14 '12 at 14:22
  • 2
    Deprecated? No, but inappropriate for a lot of tasks. http://stackoverflow.com/questions/2213109/java-util-timer-is-it-deprecated – Dan Rosenstark Oct 19 '14 at 22:36
0

I have simpler solution for those people who still wondering how to check if timer is cancelled or not. You can utilize the override function from timer class something like this

val timerTask = object : TimerTask() {
   override fun cancel(): Boolean {
      isCancelled = true
      return super.cancel()
   }

   override fun run() {
      isCancelled = false
      ...
   }
}
Marfin. F
  • 434
  • 4
  • 16