Hi All,
I've been thinking about timers a bit lately and came up with this...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| package org.kramer.utils;
import java.util.ArrayList; import java.util.Iterator; import java.util.List;
public class Timer { private long lastLoopTime = System.nanoTime(); private List<Event> events = new ArrayList<Event>();
public void update() { Iterator<Event> it = events.iterator(); while (it.hasNext()) { Event event = it.next(); if (event.nextExecution <= System.nanoTime()) { event.nextExecution = System.nanoTime() + (event.frequency * 1000000); event.doEvent(); } } lastLoopTime = System.nanoTime(); } public void scheduleEvent(long frequency, Event event) { event.frequency = frequency; event.nextExecution = System.nanoTime() + (frequency * 1000000); events.add(event); }
public abstract class Event { long nextExecution; long frequency; public abstract void doEvent(); }
} |
...and in your init() you register events and how frequently you want them to happen as:
1 2 3 4 5 6 7 8 9 10 11
| Timer timer = new Timer(); timer.scheduleEvent(500, timer.new Event(){ public void doEvent() { System.out.println("every 500 milliseconds"); } }); timer.scheduleEvent(100, timer.new Event(){ public void doEvent() { System.out.println("every 100 milliseconds"); } }); |
Then call timer.update() in display().
So... does anyone think this is any good? Would you use it? If not, please let me know why.
Thanks,
Kramer