比较时间并重复执行某项任务

时间:2014-04-08 11:25:40

标签: 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()).toString();
        System.out.println(systemTime);
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用quartz-scheduler

SO answer

中给出了示例

所以,如果你想在每天,每年,每个月的上午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课程将在预定时间执行。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

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