Using Timer.schedule to make java program run at a specific time Not working

Tags: ,

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:

  1. I tried to set up a timer task first
  2. I then tried to create a Date object using the current time
  3. 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.
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() {
            public void run() {
                BookingPage page = new BookingPage();
        Date date = generateDate();
        timer.schedule(task, date);

    public static Date generateDate() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        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;


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!

Source: stackoverflow