1

I'm using JavaFX 8 to develop a little game as a side project and I want to use the Timer class from the Java.util package.

The thing is, whenever I schedule the Timer to do something, I don't know how to stop it, and it keeps running in the background even when I've already closed the window.

I eventually made a method called handleShutDown() that's called whenever the Stage is set on hidden, using the code below.

stage.setOnHidden(windowEvent -> controller.handleShutDown());

I also tried a couple of different ways to cancel the Timer in the handleShutDown() method. I tried calling the Timer's cancel() method, the Timer's purge() method, setting the Timer to null, and even replacing the Timer with a new one (timer = new Timer()).

public void handleShutDown() {
//    timer.cancel();
//    timer.purge();
//    timer = new Timer();
    timer = null;
    Platform.exit();
}

I'm not sure what to try next...

Here's how I know the application is still running, since the red box is still there even after I closed the window, which should not happen. And everything was fine until I started using timers. Or maybe I shouldn't use a Timer?

Here's how I know the application is still running

Thanks in advance.

  • 2
    Your application keeps running because a user thread is still alive. See [What is a Daemon Thread in Java](https://stackoverflow.com/questions/2213340/what-is-a-daemon-thread-in-java). This is how you start a Timer with a daemon thread: `Timer timer = new Timer(true);` – Miss Chanandler Bong Jul 29 '21 at 08:01
  • 2
    _ I want to use the Timer class from the Java.util package._ Why? Learn to use fx concurrency support – kleopatra Jul 29 '21 at 09:41
  • 1
    In case you haven't considered animations, make sure [you're using the right tool for the job](https://stackoverflow.com/questions/9966136/javafx-periodic-background-task/60685975#60685975). – Slaw Jul 29 '21 at 13:53
  • 1
    Also, could you provide a [mre], please? Calling [Timer#cancel()](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/Timer.html#cancel()) should be working for you. – Slaw Jul 29 '21 at 13:56

1 Answers1

4

To make a Thread run in the background and die when the main thread dies, use the daemon boolean property (See: Daemon Threads):

Thread thread = new Thread();
thread.setDaemon(true); // this thread will die when the main thread dies 

Timer uses TimerThread which extends Java's Thread. When constructing a timer using the no-parameters constructor, the underlying thread will be a non-daemon thread by default. To make the time run on a daemon thread you can use the Timer's constructor:

Timer timer = new Timer(true); // a timer with a daemon thread.
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36