Tom Jenkinson
Tom Jenkinson

Reputation: 1470

Java Terminating Before Timer Runs

I have the following code

new Timer(300, this).start();

and this

public void actionPerformed(ActionEvent e) {
   //do something
}

in the same class which implements ActionListener.

The problem is that the program terminates before the code in actionPerformed gets chance to run. At least I think that is what is happening!

How do I tell java to keep running when it has nothing to do?

Thanks!

Edit: It's a javax.swing.Timer

Upvotes: 1

Views: 176

Answers (2)

Boris the Spider
Boris the Spider

Reputation: 61148

The Timer uses daemon Threads - they do not prevent the program from exiting.

You using the javax.swing.Timer but it doesn't look like you are running in a Swing environment.

You need to use a java.util.Timer and make sure you create it with new Timer(false). This will build it with non daemon Threads that will keep the application open.

This means you will need to call cancel() on the Timer for your application to exit.

Upvotes: 2

Eng.Fouad
Eng.Fouad

Reputation: 117587

A Java program is terminated whenever all the non-daemon threads are finished. So, keep the main thread running or at least one of the non-daemon threads.

Upvotes: 1

Related Questions