Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can run my TimerTask everyday 2 PM?

I want to execute a job everyday 2PM. Which method of java.util.Timer I can use to schedule my job?

After 2Hrs, run it will stop the job and reschedule for next day 2PM.

like image 704
BOSS Avatar asked Feb 21 '12 10:02

BOSS


People also ask

How do I stop TimerTask?

In order to cancel the Timer Task in Java, we use the java. util. TimerTask. cancel() method.

What is the relationship between Timer and TimerTask?

Timer provides method to schedule Task where the task is an instance of TimerTask class, which implements the Runnable interface and overrides run() method to define task which is called on scheduled time.


2 Answers

Calendar today = Calendar.getInstance(); today.set(Calendar.HOUR_OF_DAY, 2); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0);  // every night at 2am you run your task Timer timer = new Timer(); timer.schedule(new YourTask(), today.getTime(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); // period: 1 day 
like image 136
Daniel Gerber Avatar answered Oct 16 '22 14:10

Daniel Gerber


You could use Timer.schedule(TimerTask task, Date firstTime, long period) method, setting firstTime to 2PM today and the setting the period to 24-hours:

Schedules the specified task for repeated fixed-delay execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

like image 37
hmjd Avatar answered Oct 16 '22 14:10

hmjd