1

I want to execute a task periodically if time is in between

9 AM to 9:11 AM 

I was able to capture the current time, but could please tell me how can I compare that with the above condition ??

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);
    }
}
Vincent Guerci
  • 14,379
  • 4
  • 50
  • 56
Pawan
  • 31,545
  • 102
  • 256
  • 434
  • u may try using [Timer](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html#scheduleAtFixedRate%28java.util.TimerTask,%20java.util.Date,%20long%29) –  Apr 08 '14 at 11:37
  • use a Timer and check Time between – Benjamin Apr 08 '14 at 11:37

3 Answers3

1

You can use quartz-scheduler.

Example is given in this SO answer

So if you want to run job between 9 AM to 9:11 AM every day, every year, every month. You can use following cron time notation.

//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();

Here, MyTest class will be executed at scheduled time.

Community
  • 1
  • 1
Not a bug
  • 4,286
  • 2
  • 40
  • 80
1

You can use while loop to achieve that:

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;
}
sendon1982
  • 9,982
  • 61
  • 44
0

You can use this. This will give you hour and minute fields which you can compare.

Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
JManish
  • 321
  • 4
  • 17
  • I see you're using "Code Sample" (Ctrl-K) for non-code in most of your answers, even after it's been corrected by others in your previous answers. When posting a post containing code, be sure to select **just** the code before pressing the "Code Sample" button or Ctrl-K. – Bernhard Barker Apr 08 '14 at 13:59