【问题标题】:Compare time and execute some a task repeatedly比较时间并重复执行某项任务
【发布时间】:2014-04-08 11:25:40
【问题描述】:

如果时间间隔,我想定期执行任务

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

【问题讨论】:

  • 你可以尝试使用Timer
  • 使用计时器并检查间隔时间

标签: java date


【解决方案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】:

    您可以使用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 类将在预定时间执行。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 我看到您在大多数答案中都使用“代码示例”(Ctrl-K)来表示非代码,即使在您之前的答案中已被其他人更正之后也是如此。发布包含代码的帖子时,请务必在按“代码示例”按钮或 Ctrl-K 之前选择代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多