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.
In order to cancel the Timer Task in Java, we use the java. util. TimerTask. cancel() method.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With