[英]How do we still run a method every X seconds if the method itself takes some time?
[英]Run a method every X seconds
我正在用Java创建一个基于文本的游戏,这是我自己的第一个官方程序。 它是带有饥饿,口渴和体温变量的生存游戏。
可以说,我希望饥饿感和饥饿感每5秒左右减少一次。 目前,我只能上班的是这个。 这肯定会减少数字,但会在2秒内从100变为0。
public void run(){
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
delta--;
}
}
private void tick(){
Health.playerHealth.tick();
}
///////////////////////////////////////////////
public static Health playerHealth = new Health();
private static int hunger = 100;
private static int thirst = 100;
private static double bodyTemperature = 98.6;
public void tick(){
depleteHunger();
depleteThirst();
depleteBodyTemperature();
}
public void depleteHunger(){
hunger--;
}
public void depleteThirst(){
thirst--;
}
我试过这个定时器为好,但它只是等待5秒我把THEN降低从100到0瞬间
private void tick(){
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
depleteHunger();
depleteThirst();
depleteBodyTemperature();
}
}, 0, 5000);
}
可能您可以看看计时器的scheduleAtFixedRate
:
示例示例:
Timer timerObj = new Timer(true);
timerObj.scheduleAtFixedRate(timerTask, 0, interval));
该方法基本上可以实现您想要实现的目标:以特定的时间间隔执行任务。 您需要通过覆盖run()
方法并将逻辑放入其中来初始化TimerTask
对象(正如您在代码中也提到的那样)。
final int TICKS_PER_SECOND = 20;
final int TICK_TIME = 1000 / TICKS_PER_SECOND;
while (running) {
final long startTime = System.currentTimeMillis();
// some actions
final long endTime = System.currentTimeMillis();
final long diff = endTime - startTime;
if (diff < TICK_TIME) {
try {
Thread.sleep(TICK_TIME - diff);
} catch (Exception e) {
e.printStackTrace();
}
}
}
找到了解决方案。
public class HealthStatsTimer extends TimerTask {
public void run() {
Health.playerHealth.depleteHunger();
Health.playerHealth.depleteThirst();
Health.playerHealth.depleteBodyTemperature();
}
}
//////////////////////
public static void main(String[] args){
new Stranded();
Timer timer = new Timer();
timer.schedule(new HealthStatsTimer(), 5000, 5000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.