Penambahan Timer untuk hitung target layanan otomatis bulanan
This commit is contained in:
parent
6d6136dda4
commit
c113ec4a6d
@ -0,0 +1,85 @@
|
||||
package com.jasamedika.medifirst2000.asynctask.timer;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class TargetLayananTimer {
|
||||
private final static Logger LOGGER = LoggerFactory.getLogger(TargetLayananTimer.class);
|
||||
|
||||
// What to do
|
||||
private final Runnable whatToDo;
|
||||
|
||||
// when
|
||||
private final int dayOfMonth;
|
||||
private final int hourOfDay;
|
||||
|
||||
// The current timer
|
||||
private Timer current = new Timer();
|
||||
|
||||
public void cancelCurrent() {
|
||||
LOGGER.info("TargetLayananTimer : Cancel current execution");
|
||||
current.cancel();
|
||||
|
||||
LOGGER.info("TargetLayananTimer : Removes the timertask so it can be garbage collected");
|
||||
current.purge();
|
||||
}
|
||||
|
||||
public static TargetLayananTimer schedule(Runnable runnable, int dayOfMonth, int hourOfDay) {
|
||||
LOGGER.info("TargetLayananTimer : Create a new instance");
|
||||
return new TargetLayananTimer(runnable, dayOfMonth, hourOfDay);
|
||||
}
|
||||
|
||||
private TargetLayananTimer(Runnable runnable, int day, int hour) {
|
||||
this.whatToDo = runnable;
|
||||
this.dayOfMonth = day;
|
||||
this.hourOfDay = hour;
|
||||
|
||||
schedule();
|
||||
}
|
||||
|
||||
private void schedule() {
|
||||
cancelCurrent();
|
||||
|
||||
LOGGER.info(
|
||||
"TargetLayananTimer : Assigning a new instance of Timer, allow the previous Timer to be garbage collected");
|
||||
current = new Timer();
|
||||
current.schedule(new TimerTask() {
|
||||
public void run() {
|
||||
try {
|
||||
LOGGER.info("TargetLayananTimer : Running schedule");
|
||||
whatToDo.run();
|
||||
} finally {
|
||||
LOGGER.info("TargetLayananTimer : Schedule for the next month");
|
||||
schedule();
|
||||
}
|
||||
}
|
||||
}, nextDate());
|
||||
}
|
||||
|
||||
private Date nextDate() {
|
||||
Calendar runDate = Calendar.getInstance();
|
||||
if (runDate.get(Calendar.DAY_OF_MONTH) < dayOfMonth) {
|
||||
runDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
|
||||
runDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
|
||||
runDate.set(Calendar.MINUTE, 0);
|
||||
runDate.set(Calendar.SECOND, 0);
|
||||
runDate.set(Calendar.MILLISECOND, 0);
|
||||
} else {
|
||||
runDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
|
||||
runDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
|
||||
runDate.set(Calendar.MINUTE, 0);
|
||||
runDate.set(Calendar.SECOND, 0);
|
||||
runDate.set(Calendar.MILLISECOND, 0);
|
||||
runDate.add(Calendar.MONTH, 1);
|
||||
}
|
||||
|
||||
LOGGER.info("MonthlyTimer : Set to next month " + runDate.getTime());
|
||||
|
||||
return runDate.getTime();
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user