Java调度程序过了一段时间就不能工作了



我的调度程序有问题,我想在特定时间运行我的程序。然而,它工作得很好,但停止了工作。我不能具体说明问题所在在此处输入图像描述

我的代码

import java.util.*;
import java.text.*;
import java.util.TimerTask ;


public class ScheduleTask {

static DateFormat df = new SimpleDateFormat("HH:mm:ss");
static Date currentDate=new Date();
static Timer timer = new Timer();


public static void main(String[] args) throws ParseException {

System.out.println("Current Time: " + df.format( currentDate));

//Date and time at which you want to execute
Date date = df.parse("13:57:35");

timer.schedule(new MyTimeTask(), date);

Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, 1);
date=c.getTime();
System.out.print(date);




}


private static class MyTimeTask extends TimerTask {
public void run() {
System.out.println("Running Task");

System.out.println("Current Time: " +  df.format(currentDate));

timer.cancel();

}}

}

您可以使用TimerTask来完成此操作,下面是一个示例:

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class StopApp {
Timer timer = new Timer();
TimerTask StopApp = new TimerTask() {
@Override
public void run() {
System.exit(0);
}
};
public StopApp() {
//timer.schedule(exitApp, getDateDiff(new Date("get the actual time"), new Date("get the time you want to stop your app"), TimeUnit.SECONDS));
//Example
timer.schedule(StopApp, new Date(System.currentTimeMillis()+2*1000));//Exits after 2 sec of starting the app
while(true)
System.out.println("The App still turn");
}
public static Date getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
Date date=new Date(diffInMillies);
return date;//timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
new StopApp();
}
}

相关内容

最新更新