user3420034
user3420034

Reputation:

Schedule something for a specific time in Java?

I need to run a scheduled task at a specific time every day.

I have this so far:

Date timeToRun = new Date(System.currentTimeMillis());
Timer myTimer = new Timer();

myTimer.schedule(new TimerTask() {
    public void run() {
        //Method to run
    }
}, timeToRun);

How would I set timeToRun to a specific time? So that I can run this code on any particular date, and it would run the task at the correct time; e.g. 7:30pm every day.

Upvotes: 1

Views: 5683

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 340118

ScheduledExecutorService

The ScheduledExecutorService interface was added to Java 5 to serve your purpose.

An alternative to Timer. Both have pros and cons you should study before choosing.

In particular beware that…

If any execution of the task encounters an exception, subsequent executions are suppressed.

As described in this humorous post, the service silently quits running any more executions if any exception is thrown. One workaround I use is to wrap the entire code being run with general try-catch (and log) for the most generic Exception.

Upvotes: 0

hellboy
hellboy

Reputation: 2252

If you are trying to create a date object with specific time, here is the code -

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,19);
cal.set(Calendar.MINUTE,30);

Date timeoRun = cal.getTime();

Editing to accommodate the requirement as posted in the comment -

if(System.currentTimeMillis()>timeToRun.getTime()){
    cal.add(Calendar.DATE,1);
}
timeToRun = cal.getTime();
System.out.println(timeToRun);

In the above code, checking if the current time is greater than the computed time, if so, increment the date.

Upvotes: 2

drkunibar
drkunibar

Reputation: 1337

It's onliny an argument more

myTimer.schedule(new TimerTask() {
    public void run() {
        //Method to run
    }
}, timeToRun, 24*60*60*1000);

Upvotes: 0

user3459148
user3459148

Reputation: 19

import java.util.Timer;
import java.util.TimerTask;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;

public final class FetchMail extends TimerTask {

/** Construct and use a TimerTask and Timer. */
public static void main (String... arguments ) {
TimerTask fetchMail = new FetchMail();
//perform the task once a day at 4 a.m., starting tomorrow morning
//(other styles are possible as well)
Timer timer = new Timer();
timer.scheduleAtFixedRate(fetchMail, getTomorrowMorning4am(), fONCE_PER_DAY);
}

/**
* Implements TimerTask's abstract run method.
*/
@Override public void run(){
//toy implementation
System.out.println("Fetching mail...");
}

// PRIVATE

//expressed in milliseconds
private final static long fONCE_PER_DAY = 1000*60*60*24;

private final static int fONE_DAY = 1;
private final static int fFOUR_AM = 4;
private final static int fZERO_MINUTES = 0;

private static Date getTomorrowMorning4am(){
Calendar tomorrow = new GregorianCalendar();
tomorrow.add(Calendar.DATE, fONE_DAY);
Calendar result = new GregorianCalendar(
tomorrow.get(Calendar.YEAR),
tomorrow.get(Calendar.MONTH),
tomorrow.get(Calendar.DATE),
fFOUR_AM,
fZERO_MINUTES
);
return result.getTime();

}


}

Here, a task is performed once a day at 4 a.m., starting tomorrow morning using Timer and TimerTask.

Upvotes: 0

Related Questions