Quick Timer Question

Hi, I’m going to incorporate timers into my Slick 2D game but when I declared

Timer timer = new Timer();

I get three import options.
Do I want to import from java.util, javax.swing, or javax.management.timer?
It works perfectly fine with java.util but I was wondering if there is a significant difference between them.
Thanks for your time and help.

Don’t use any of those – write your own timer class that utilizes Slick’s update loop and delta timing.


int time = 0;
int delay = 1000; //e.g. 1 second

public void update(int delta) {
    time += delta;
    if (time >= delta) {
    	time -= delta
    	listener.trigger();
    }
}

Technical note:

You should cap your maximum logic interval (i.e. max delta) using the GameContainer method, otherwise you may get weird timing results when the delta spikes. Alternatively, you can use the following code instead, which works fine for most games although it isn’t 100% accurate:

...
if (time >= delta) {
    time = 0;
    listener.trigger();
}
...

Doesn’t that use CPU whereas a Timer sleeps?

Is the “management” Timer new with Java 7?

I always preferred the util Timer, as the Swing Timer can really clog up the EDT.

You might be interested to know that “Java Concurrency in Practice” (authors include: Biran Goetz, Joshua Bloch, Doug Lea), they say that one should prefer a ScheduledThreadPoolExecutor to a Timer, that it does a better job of handling unchecked exceptions.

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

[quote]A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.
[/quote]

You want your CPU to idle in the moment?

Yeah, I only need to do a few if statements every second, nothing in-between.

Don’t use separate threads for logic :wink:

Sorry for the delayed response and a huge thanks for everyone that replied to this thread, I’ve learned a lot thus far.
Now that I’ve thought about it I don’t even need a Timer, I can just adjust the code to go into my update method. For future reference though I don’t even want to use a Timer or a ThreadPoolExecuter as Philfrei suggest but I’d want to set up what davedes showed me, correct?