WarpPI/core/src/main/java/it/cavallium/warppi/util/Timer.java

34 lines
845 B
Java
Raw Normal View History

2019-11-01 15:23:34 +01:00
package it.cavallium.warppi.util;
2019-11-01 18:04:01 +01:00
import it.cavallium.warppi.WarpPI;
2019-11-01 15:23:34 +01:00
import java.util.concurrent.atomic.AtomicLong;
public class Timer {
public Timer(int intervalMillis, Runnable action) {
var thread = new Thread(() -> {
try {
2019-11-01 18:04:01 +01:00
Thread.sleep(intervalMillis);
2019-11-01 15:23:34 +01:00
AtomicLong lostTime = new AtomicLong();
while (!Thread.interrupted()) {
var time1 = System.currentTimeMillis();
action.run();
var time2 = System.currentTimeMillis();
var deltaTime = time2 - time1 + lostTime.get();
if (intervalMillis - deltaTime > 0) {
Thread.sleep(intervalMillis);
} else {
lostTime.set(deltaTime - intervalMillis);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
2019-11-01 18:04:01 +01:00
WarpPI.getPlatform().setThreadName(thread, "Timer");
2019-11-01 15:23:34 +01:00
thread.setDaemon(true);
thread.start();
}
}