views:

620

answers:

4

Right now, I have code that looks something like this:

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

According to what I'm seeing (and the Javadocs for the Timer class), the timer will wait 5000 milliseconds (5 seconds), fire the action event, wait 5000 milliseconds, fire again, and so on. However, the behavior that I'm trying to obtain is that the timer is started, the event is fired, the timer waits 5000 milliseconds, fires again, then waits before firing again.

Unless I missed something, I don't see a way to create a timer that doesn't wait before firing. Is there a good, clean way to emulate this?

+5  A: 

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

If you need no wait before the first firing:

timer.setInitialDelay(0);
asalamon74
Is that the only way? I would like to do it in the constructor, if possible, but it appears that isn't possible. Which kind of sucks...
Thomas Owens
No such constructor. Do not know why.
asalamon74
Could you also add your comment about this not being able to be set via a constructor to your posting, as well? That would just make it better for people searching. Thanks for your help.
Thomas Owens
A: 

I wouldn't use a Timer at all, but instead use a ScheduledExecutorService

import java.util.concurrent.*

...

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(myRunnable, 0, 5, TimeUnit.SECONDS);

Please note that there is scheduleAtFixedRate() and scheduleWithFixedDelay() which have slightly different semantics. Read the JavaDoc and find out which one you need.

Joachim Sauer
Updates to Swing components should be done on the EDT. A Swing Timer does execute in the EDT. From the reading I've done the ScheduledExecutorService does not execute in the EDT and should not be used with Swing.
camickr
A: 

Simple solution:

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

But I like timer.setInitialDelay(0) a lot better.

Bombe
A: 

I am not sure if this will be of much help, but:

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