Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 比较时间并重复执行任务_Java_Date - Fatal编程技术网

Java 比较时间并重复执行任务

Java 比较时间并重复执行任务,java,date,Java,Date,如果时间介于两者之间,我希望定期执行任务 9 AM to 9:11 AM 我能够捕捉到当前时间,但请告诉我如何将其与上述条件进行比较 public class Test { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); String systemTime = sdf.format(new Date())

如果时间介于两者之间,我希望定期执行任务

9 AM to 9:11 AM 
我能够捕捉到当前时间,但请告诉我如何将其与上述条件进行比较

public class Test  {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String systemTime = sdf.format(new Date()).toString();
        System.out.println(systemTime);
    }
}
你可以用

本文给出了一个例子

所以,如果您想在每天、每年、每月的上午9点到上午9:11点之间运行作业。您可以使用以下cron时间表示法

//Create instance of factory
SchedulerFactory schedulerFactory=new StdSchedulerFactory();

//Get schedular
Scheduler scheduler= schedulerFactory.getScheduler();

//Create JobDetail object specifying which Job you want to execute
JobDetail jobDetail=new JobDetail("myTestClass","myTest",Test.class);

//Associate Trigger to the Job
CronTrigger trigger=new CronTrigger("cronTrigger","myTest","1-11 9 * * * *");

//Pass JobDetail and trigger dependencies to schedular
scheduler.scheduleJob(jobDetail,trigger);

//Start schedular
scheduler.start();

在这里,
MyTest
类将在预定时间执行。

您可以使用它。这将为您提供可以比较的小时和分钟字段

Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);

您可以使用while循环来实现这一点:

public static void main(String[] args) {

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    String systemTime = sdf.format(new Date()).toString();

    String START = "09:00:00";
    String END = "09:11:00";

    while (compareTime(systemTime, START, END))
    {
        System.out.println("Your task here");
        systemTime = sdf.format(new Date()).toString();
    }
}

private static boolean compareTime(String systemTime, String START, String END)
{
    return systemTime.compareTo(START) >= 0 && systemTime.compareTo(END) <= 0;
}
publicstaticvoidmain(字符串[]args){
SimpleDataFormat sdf=新的SimpleDataFormat(“HH:mm:ss”);
字符串systemTime=sdf.format(new Date()).toString();
字符串START=“09:00:00”;
字符串结束=“09:11:00”;
while(比较时间(系统时间、开始、结束))
{
System.out.println(“此处的任务”);
systemTime=sdf.format(new Date()).toString();
}
}
私有静态布尔比较时间(字符串systemTime、字符串开始、字符串结束)
{

return systemTime.compareTo(START)>=0&&systemTime.compareTo(END)您可以尝试使用计时器并检查两个时间之间的时间,我看到您正在使用“代码示例”(Ctrl-K)对于大多数答案中的非代码,即使在您以前的答案中已被他人更正后也是如此。发布包含代码的帖子时,请确保在按下“代码示例”按钮或Ctrl-K之前仅选择代码。