java调度程序在一段时间后不工作

v7pvogib  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(433)

我的计划程序有问题,我想在特定时间运行我的程序。但是,它工作正常,但停止工作。我无法指定问题。请在此处输入图像描述
我的代码

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

   }}

   }
0lvr5msh

0lvr5msh1#

您可以使用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();

}
}

相关问题