00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 package com.realtime.crossfire.jxclient.items;
00023
00024 import java.lang.reflect.InvocationTargetException;
00025 import javax.swing.SwingUtilities;
00026 import org.jetbrains.annotations.NotNull;
00027
00036 public class EventScheduler {
00037
00042 private final int delay;
00043
00048 private final int afterEventDelay;
00049
00053 @NotNull
00054 private final Runnable eventSchedulerCallback;
00055
00060 @NotNull
00061 private final Object sync = new Object();
00062
00066 @NotNull
00067 private final Thread thread;
00068
00073 private long nextAction = 0;
00074
00078 private long nextActionNotBefore = System.currentTimeMillis();
00079
00084 @NotNull
00085 private final Runnable runnable = new Runnable() {
00086
00087 @Override
00088 public void run() {
00089 while (true) {
00090 try {
00091 final long now = System.currentTimeMillis();
00092 final boolean fireEvent;
00093 synchronized (sync) {
00094 if (nextAction == 0) {
00095 sync.wait();
00096 fireEvent = false;
00097 } else {
00098 final long delay = Math.max(nextAction, nextActionNotBefore)-now;
00099 if (delay > 0) {
00100 sync.wait(delay);
00101 fireEvent = false;
00102 } else {
00103 fireEvent = true;
00104 }
00105 }
00106 }
00107
00108 if (fireEvent) {
00109 try {
00110 SwingUtilities.invokeAndWait(eventSchedulerCallback);
00111 } catch (final InvocationTargetException ex) {
00112 throw new AssertionError(ex);
00113 }
00114 nextAction = 0;
00115 nextActionNotBefore = System.currentTimeMillis()+afterEventDelay;
00116 }
00117 } catch (final InterruptedException ignored) {
00118 thread.interrupt();
00119 break;
00120 }
00121 }
00122 }
00123
00124 };
00125
00132 public EventScheduler(final int delay, final int afterEventDelay, @NotNull final Runnable eventSchedulerCallback) {
00133 this.delay = delay;
00134 this.afterEventDelay = afterEventDelay;
00135 this.eventSchedulerCallback = eventSchedulerCallback;
00136 thread = new Thread(runnable, "JXClient:EventScheduler");
00137 }
00138
00142 public void start() {
00143 thread.start();
00144 }
00145
00149 public void trigger() {
00150 final long now = System.currentTimeMillis();
00151 synchronized (sync) {
00152 nextAction = now+delay;
00153 sync.notifyAll();
00154 }
00155 }
00156
00157 }