나는 하루 중 특정 순간에 실행해야하는 타이머 스레드가 있습니다. 데이터베이스를 사용한 증분 복제. 지금은 1 시간 15 분, 1 시간 30 분, 1 시간 45 분으로 실행됩니다. 이 프로세스는 TimerRunner.initialize()
때 서버가 시작를 호출 TimerRunner.destroy()
를 호출하여 시작x : 00 x : 15 x : 30 및 x : 45에서 실행되는 스레드를 만드는 방법 2:00에서 다른 작업 수행
public class TimerRunner implements Runnable {
private static final Semaphore lock = new Semaphore(1);
private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
public static void initialize() {
long delay = getDelay();
executor.schedule(new TimerRunner(), delay, TimeUnit.SECONDS);
}
public static void destroy() {
executor.shutdownNow();
}
private static long getDelay() {
Calendar now = Calendar.getInstance();
long p = 15 * 60; // run at 00, 15, 30 and 45 minutes past the hour
long second = now.get(Calendar.MINUTE) * 60 + now.get(Calendar.SECOND);
return p - (second % p);
}
public static void replicate() {
if (lock.tryAcquire()) {
try {
Thread t = new Thread(new Runnable() {
public void run() {
try {
// here is where the magic happens
} finally {
lock.release();
}
}
});
t.start();
} catch (Exception e) {
lock.release();
}
} else {
throw new IllegalStateException("already running a replicator");
}
}
public void run() {
try {
TimerRunner.replicate();
} finally {
long delay = getDelay();
executor.schedule(new TimerRunner(), delay, TimeUnit.SECONDS);
}
}
}
이 괜찮 노력하고 내가 가지고있는 코드입니다.
하루 중 특정 순간 (예 : 오전 2시)에 실행하려는 전체 복제 프로세스 (증분과 반대)를 만들었습니다. 어떻게 이렇게 위의 코드를 변경하겠습니까? 나는 마치 2:00 경에 마치 지금은 전체 복제를했기 때문에 오랜 시간이 걸렸을 때와 같이 매우 간단해야한다고 생각합니다. 그렇지만 지금은 제대로 할 수 없습니다.
때로는 복제 프로세스를 완료하는 데 시간이 오래 걸리는 것을 유의하십시오. 때로는 15 분을 초과하여 오전 2 시경에 달리는 데 문제가 있습니다.
두 스케줄러의 한 가지 문제점은 오전 2시에 증분과 전체를 실행해야하지만 전체가 필요하다는 것입니다. 두 가지 예정된 프로세스 간의 경쟁 조건을 확인하는 방법? – rmarimon
@rmarimon. 나는 당신의 의견을 해결하기 위해 내 대답을 업데이 트했습니다. –