[英]Use of Timer in Java
我正在為電影院編寫票務預訂系統。 我想啟動一個計時器,讓用戶在選擇座位后有 5 分鍾的時間結帳。 我決定使用 java 的 Timer class。
這是啟動計時器的代碼,以及被調用的expiredCheckout()
function:
private void expiredCheckout() {
Scanner inputObj = new Scanner(System.in);
while (true) {
System.out.println("Your session has expired!");
System.out.println("If you want to start over, press 1");
System.out.println("If you want to cancel, press q");
String input = inputObj.next();
System.out.println("made it here");
if (input.equals("q"))
return;
else if (input.equals("1")) {
this.runTheatreUI();
break;
} else {
System.out.println("Please enter valid choice!");
}
}
}
private void startTimer(ArrayList<Seat> seatsSelected) {
Timer timer = new Timer();
timer.schedule(
new TimerTask() {
public void run() {
expiredCheckout();
return;
}
}
,5*60*1000);
ArrayList<Object> checkoutInfo = this.checkout();
timer.cancel();
if (checkoutInfo.get(0).equals(true)) {
for (int i = 0; i < seatsSelected.size(); i++) {
seatsSelected.get(i).setStatus(Seat.TAKEN);
this.numSeatsAvailable += 1;
}
} else {
// the user quit
for (int i = 0; i < seatsSelected.size(); i++) {
seatsSelected.get(i).setStatus(Seat.OPEN);
this.numSeatsAvailable += 1;
}
}
return;
}
如您所見,我在讀取用戶輸入后添加了打印語句。 然而,function 從未成功過。 當我在終端中輸入一個字符時,沒有任何動作。 我很困惑為什么會這樣。
要取消計時器,您可以在 TimerTask 本身中執行此操作
private void expiredCheckout() {
System.out.println("in expired method");
Scanner inputObj = new Scanner(System.in);
while (true) {
System.out.println("Your session has expired!");
System.out.println("If you want to start over, press 1");
System.out.println("If you want to cancel, press q");
String input = inputObj.nextLine();
System.out.println("made it here");
if (input.equals("q")) {
System.out.println("quitting");
timer.cancel();
timer.purge();
return;
}
else if (input.equals("1")) {
System.out.println("Entered 1");
break;
} else {
System.out.println("Please enter valid choice!");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.