timertask—使用timer.schedule使java程序在特定时间运行而不工作

zyfwsgd6  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(350)

我正在尝试使用timer.schedule()使任务在特定时间自动运行。然而,它不起作用。我的代码:
我试着先设置一个计时器任务
然后我尝试使用当前时间创建一个日期对象
然后我使用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;
    }
}
cgyqldqp

cgyqldqp1#

我认为这解决了问题

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();
    }
}
jgwigjjp

jgwigjjp2#

执行日历时。设置(年、月、日、时、分、秒)月必须比当前月少一个月。例如,五月是4。问题解决了!

相关问题