[英]Using Timer.schedule to make java program run at a specific time Not working
我正在嘗試使用 Timer.schedule() 使任務在特定時間自動運行。 但是,它不起作用。 我的代碼:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args){
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Starts");
BookingPage page = new BookingPage();
page.logIn();
page.selectCourseAndTime();
page.finishSelectTime();
}
};
Date date = generateDate();
timer.schedule(task, date);
}
public static Date generateDate() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDateTime now = LocalDateTime.now();
String[] arr = dtf.format(now).split("/");
int[] currentTime = new int[arr.length];
for (int i = 0; i < currentTime.length; i++) {
currentTime[i] = Integer.parseInt(arr[i]);
}
Calendar calendar = Calendar.getInstance();
calendar.set(currentTime[0], currentTime[1], currentTime[2], 15, 24, 0);
Date date = calendar.getTime();
return date;
}
}
我認為這解決了問題
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask {
@Override
public void run() {
System.out.println("Timer task started at:"+new Date());
completeTask();
System.out.println("Timer task finished at:"+new Date());
}
private void completeTask() {
try {
//assuming it takes 20 secs to complete the task
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
TimerTask timerTask = new MyTimerTask();
//running timer task as daemon thread
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 10*1000);
System.out.println("TimerTask started");
//cancel after sometime
try {
Thread.sleep(120000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
System.out.println("TimerTask cancelled");
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
在做 calendar.set(year, month, day, hour, minute, second) 時,月份需要比當前月份少一個。 例如,May是4。問題解決了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.