Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule Java task for a specified time

I would like to be able to schedule a task at a specific time in Java. I understand that the ExecutorService has the ability to schedule at periodic intervals, and after a specified delay, but I am looking more for a time of day as opposed to after a duration.

Is there a way to have, say, a Runnable execute at 2:00, or do I need to calculate the time between now and 2:00, and then schedule the runnable to execute after that delay?

like image 522
Ray Avatar asked Nov 09 '11 14:11

Ray


3 Answers

you can use spring annotations too

@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
// something that should execute on weekdays only
}

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

like image 165
Peter Szanto Avatar answered Nov 06 '22 04:11

Peter Szanto


this is how I've solved it using java7SE:

    timer = new Timer("Timer", true);
    Calendar cr = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    cr.setTimeInMillis(System.currentTimeMillis());
    long day = TimeUnit.DAYS.toMillis(1);
    //Pay attention - Calendar.HOUR_OF_DAY for 24h day model 
    //(Calendar.HOUR is 12h model, with p.m. a.m. )
    cr.set(Calendar.HOUR_OF_DAY, it.getHours());
    cr.set(Calendar.MINUTE, it.getMinutes());
    long delay = cr.getTimeInMillis() - System.currentTimeMillis();
    //insurance for case then time of task is before time of schedule
    long adjustedDelay = (delay > 0 ? delay : day + delay);
    timer.scheduleAtFixedRate(new StartReportTimerTask(it), adjustedDelay, day);
    //you can use this schedule instead is sure your time is after current time
    //timer.scheduleAtFixedRate(new StartReportTimerTask(it), cr.getTime(), day);

it happens to be trickier than I thought to do it correctly

like image 6
theme Avatar answered Nov 06 '22 03:11

theme


You'll be wanting Quartz.

like image 4
Duncan McGregor Avatar answered Nov 06 '22 04:11

Duncan McGregor