Reputation: 32321
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);
}
}
Upvotes: 1
Views: 186
Reputation: 331
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);
Upvotes: 0
Reputation: 11234
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;
}
Upvotes: 1
Reputation: 4314
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.
Upvotes: 1