在Java中安排任务的指定日期 [英] Scheduling a task in Java for a specified date

查看:136
本文介绍了在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

这篇关于在Java中安排任务的指定日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆