簡體   English   中英

使用 Timer.schedule 使 java 程序在特定時間運行 不工作

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

我正在嘗試使用 Timer.schedule() 使任務在特定時間自動運行。 但是,它不起作用。 我的代碼:

  1. 我試着先設置一個計時器任務
  2. 然后我嘗試使用當前時間創建一個 Date 對象
  3. 然后我使用 Timer.schedule(timertask, date) 告訴計算機何時執行任務。 但是,timertask 不會在指定日期開始。 請幫忙,謝謝。
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM