How do you create javax.swing.Timer that fires immediately and then every t milliseconds?

Now I have a code that looks something like this:

Timer timer = new javax.swing.Timer(5000, myActionEvent); 

According to what I see (and Javadocs for the Timer class , the timer will wait 5,000 milliseconds (5 seconds), fire an action event, wait 5,000 milliseconds, fire again, etc. However, the behavior I'm trying to get, is that the timer starts, the event fires, the timer waits 5,000 milliseconds, fires again, and then waits before firing again.

If I missed something, I see no way to create a timer that does not wait until it starts. Is there a good, clean way to emulate this?

+4
source share
4 answers

You can specify only a delay in the constructor. You need to change the initial delay (time before the start of the first event). You cannot set in constuctor, but you can use the setInitialDelay method of the Timer class.

If you do not need to wait until the first shooting:

 timer.setInitialDelay(0); 
+10
source

I am not sure if this will be very useful, but:

 Timer timer = new javax.swing.Timer(5000, myActionEvent){{setInitialDelay( 0 );}}; 
+2
source

I would not use a timer at all, but use a ScheduledExecutorService instead

 import java.util.concurrent.* ... ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleAtFixedRate(myRunnable, 0, 5, TimeUnit.SECONDS); 

Note that there are scheduleAtFixedRate() and scheduleWithFixedDelay() , which have slightly different semantics. Read the JavaDoc and find out which one you need.

0
source

A simple solution:

 Timer timer = new javax.swing.Timer(5000, myActionEvent); myActionEvent.actionPerformed(new ActionEvent(timer, 0, null)); 

But I like the timer. setInitialDelay (0) much better.

0
source

All Articles