import java.awt.event.*; public class Timer250 { private long period; private ActionListener listener; private Timer250Thread t2t; public Timer250(long period, ActionListener listener) { this.period = period; this.listener = listener; t2t = null; } public void start() { stop(); t2t = new Timer250Thread(); t2t.start(); } public void stop() { if (t2t != null) {t2t.halt();} } private class Timer250Thread extends Thread { private boolean going; private long nextTick; public Timer250Thread() { super(); going = false; } public void run() { going = true; ActionEvent ae = new ActionEvent(Timer250.this, 0, "TickTock"); nextTick = System.currentTimeMillis(); while (going) { if (System.currentTimeMillis() >= nextTick) { listener.actionPerformed(ae); nextTick += period; } } } public void halt() { going = false; } public boolean isRunning() {return going;} } public static void main(String[] args) { if (args.length == 0) { System.out.println("Usage: Timer250 period"); } int period = Integer.parseInt(args[0]); ActionListener al = new ActionListener() { private int ct = 0; public void actionPerformed(ActionEvent e) { ct += 1; System.out.println(ct + ": " + System.currentTimeMillis()); } }; Timer250 t = new Timer250(period, al); t.start(); long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() < startTime + 1000) {} t.stop(); } }