我正在尝试在一天的特定时间安排一个线程,例如每天凌晨4点,即使在发现异常后也要重新安排时间。
我在应用程序启动时安排了一个线程,该线程在执行结束时使用简单的ScheduledThreadPoolExecutor.schedule(new ThreadItself)重新安排了自己的时间。但是我需要为线程指定初始延迟。我知道scheduleAtFixedDelay / Rate,但是从文档开始,如果有异常,它的确停止了线程的下一次执行。
我有这个
MyScheduler内部
public class MyScheduler{
public void init(){
ScheduledThreadPoolExecutor myScheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
myScheduledThreadPoolExecutor.schedule(new MyThread(), delay, TimeUnit.HOURS);
}
public void scheduleNextMyThread(int delay){
myScheduledThreadPoolExecutor.schedule(new MyThread(), delay, TimeUnit.HOURS);
}
}
在线程内
public class MyThread extends Thread {
private MyScheduler myScheduler;
public MyThread(Thread scheduler) {
this.myScheduler = scheduler;
}
@Override
public void run() {
try {
// Try Work
} catch (Exception exc) {
// Catch Exception
} finally {
// Reschedule myself
myScheduler.scheduleNextMyThread(delay);
}
}
}
我要实现的目标是使用scheduleAtFixedRate()在特定时间重新安排MyThread来设置初始延迟并重新安排本身。
我最终写了这个
Inside MyScheduler
myScheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
public void scheduleMyThreadAtFixedRate(int delay){
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)+1, 4, 0, 0);
myScheduledThreadPoolExecutor.scheduleAtFixedRate(new MyThread(), initialDelay, delay, TimeUnit.HOURS);
}
在MyThread内部
public class MyThread extends Thread {
private Scheduler scheduler;
public MyThread(Thread scheduler) {
this.scheduler = scheduler;
}
@Override
public void run() {
try {
// Try Work
} catch (Exception exc) {
// Catch Exception
// HERE IS MY DOUBT. IS THIS NECESSARY?
myScheduler.scheduleMyThreadAtFixedRate(delay);
}
}
}
所以...捕获到异常。是否有必要在catch块内重新安排MyThread的时间,还是因为没有引发异常而使它继续其正常的时间安排?