在Java中安排任务的指定日期

在Java中安排任务的指定日期

问题描述:

我期待学习Java。我编写了此程序,以便当当前日期与指定日期匹配时,它将执行一些代码,在这种情况下,它将退出while循环。
我想知道是否还有其他方法,但是现在我会坚持使用此字符串比较。

i am looking forward to learn java. I made this program , so that when the current date matches the specified date, it will execute some code, in this case, it will exit the while loop. I'd like to know if there any other ways, but for now i will stick with this string comparison.

由于某些原因,If循环为'为了正常工作,我使用System.out.println(date)监视当前日期,但是当它达到所需日期(通过格式HH:MM:SS)执行操作时,字符串不相等,并且while循环继续,有什么我想念的吗?

For somewhat reasons the If loop isn't working properly, i monitor the current date with System.out.println(date) but when it reaches the desired date (by format HH:MM:SS) to do the action,the strings aren't equal and the while loop continues, is there anything i miss?

编辑:平台= Windows 7

Platform = windows 7

public class Main {

static String DesiredDate;
static String date;
static boolean Programisrunning;

public static void main(String[] args) {

DesiredDate = "17:24:10";

 while(Programisrunning = true) {

     date = CurrentDate.GetDate();
     System.out.println(date);

     if(date.equals(DesiredDate)) {
         Programisrunning = false;
        }

    }

 System.out.println("Program succesfully terminated");

   }

}

// class

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CurrentDate {

public static String GetDate(){
       DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

       Date date = new Date();
       return dateFormat.format(date);
     }

   }


要安排任务,请使用 ScheduledExecutorService

To schedule a task, use a ScheduledExecutorService:

Date desiredDate = // ...
Date now = new Date();
long delay = desiredDate.getTime() - now.getTime();

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.schedule(new Runnable(){
    @Override
    public void run() {
        Programisrunning = false;
        // + do other things?
    }
}, delay, TimeUnit.MILLISECONDS); // run in "delay" millis