Я бы порекомендовал использовать в этом режиме в реальном времени.Вам просто нужно иметь 2 переменные (время последней подачи и время сейчас), чтобы иметь возможность сделать это.Просто рассчитайте разницу во времени и поместите ее в свое условие if.См. Образец ниже:
import java.util.Date;
public class Main {
public static Date lastDate = new Date();
public static int food = 0;
public static void main(String args[]) {
System.out.println("Food was added on " + lastDate.toString() + ". Food now is " + food);
while (food < 5) {
update();
}
}
public static void update() {
Date dateNow = new Date();
// in milliseconds
long diff = dateNow.getTime() - lastDate.getTime();
long diffSeconds = diff / 1000 % 60;
// long diffMinutes = diff / (60 * 1000) % 60;
// long diffHours = diff / (60 * 60 * 1000) % 24;
// long diffDays = diff / (24 * 60 * 60 * 1000);
// If more than 5 seconds have passed
if (diffSeconds > 5) { // just change this to your desired interval
lastDate = new Date(); // get the time now
food++; // increment food
System.out.println("Food was added on " + lastDate.toString() + ". Food now is " + food);
}
}
}
Выход:
Food was added on Fri Mar 29 09:15:08 SGT 2019. Food now is 0
Food was added on Fri Mar 29 09:15:14 SGT 2019. Food now is 1
Food was added on Fri Mar 29 09:15:20 SGT 2019. Food now is 2
Food was added on Fri Mar 29 09:15:26 SGT 2019. Food now is 3
Food was added on Fri Mar 29 09:15:32 SGT 2019. Food now is 4
Food was added on Fri Mar 29 09:15:38 SGT 2019. Food now is 5