Java – Timers W/Out Threads + My Birthday!

This post was written by Brandon on December 24, 2008
Posted Under: Java

Well today (December 24th) I am another year older. Here is a special, helpful tutorial for using Timers in Java! Enjoy.
Threads can get confusing and multi-threading is no better. The use of timers is really easy and allows multiple to run at once, with different times without interference.

The first thing needed is the package to be imported:

 
import javax.swing.Timer;
 

Next, declaring the Timer:

 
Timer tmrTest = new Timer(1,myTimer);
 

The 1 is the interval in milliseconds. Meaning, this timer will execute once every millisecond, thats fast.

myTimer is just the name of the ActionListener.

Starting the timer is also necessary, it's probably best to do it in the main method.

 
tmrTest.start();
 

Next up is the action listener, this exists within the class.

 
  ActionListener myTimer = new ActionListener()
  {
    public void actionPerformed(ActionEvent evt)
    {
     //Do whatever you want to execute every millisecond
 
    }
  };
 

And thats it. You can add as many as you want. Just be sure to rename the name of the AcitonListeners and be sure to start the timers!

Helpful? Buy me a coffee for this cold Birthday-day

Reader Comments

Trackbacks

  1. Twitted by objects  on June 5th, 2009 @ 6:23 pm

Add a Comment

required, use real name
required, will not be published
optional, your blog address