I am trying to get use Timer.schedule() to make a task run automatically at a certain time. However, it is not working. my code:
- I tried to set up a timer task first
- I then tried to create a Date object using the current time
- I then use Timer.schedule(timertask, date) to tell the computer when to do the task. However, the timertask doesn’t start at the specified date. Please help, thank you.
JavaScript
x
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;
}
}
Advertisement
Answer
When doing calendar.set(year, month, day, hour, minute, second) month needs to be one less than the current month. For example, May is 4. problem solved!