我试图自动运行任务(全部30个)。
为此,我建立了一个单身人士:
public class PortalSingleton {
private static final Logger LOG = LoggerFactory.getLogger(PortalSingleton.class);
private static final int INITIAL_DELAY = 0;
private static final int DELAY = 30;
private static volatile ScheduledExecutorService instance;
private static HomepageView homeView = new HomepageView();
private PortalSingleton() {}
public static final void refreshGridHomePageAutomatically() {
Runnable task = () -> UI.getCurrent().access(() -> {
homeView.refreshGrid();
LOG.info("The grid has been refreshed Automatically");
});
getInstance().scheduleWithFixedDelay(task, INITIAL_DELAY, DELAY, TimeUnit.SECONDS);
}
public final static ScheduledExecutorService getInstance() {
if (instance == null) {
synchronized (ScheduledExecutorService.class) {
if (instance == null) {
instance = Executors.newScheduledThreadPool(1);
}
}
}
return instance;
}
}
但是,我没有任何问题/错误而且我没有我的日志消息,我的网格也没有刷新..
预期的行为是:
即使我删除了homeView.refreshGrid();
行,也没有我的日志信息...
我做错了什么?
谢谢,
编辑:我这样称呼:PortalSingleton.refreshGridHomePageAutomatically();
EDIT2,谢谢@Holger:
public class PortalSingleton {
private static final Logger LOG = LoggerFactory.getLogger(PortalSingleton.class);
private static final int INITIAL_DELAY = 0;
private static final int DELAY = 30;
private static final ScheduledExecutorService instance = Executors.newScheduledThreadPool(1);
private static HomepageView homeView = new HomepageView();
private PortalSingleton() {
}
public static final void refreshGridHomePageAutomatically() {
Runnable task = () -> UI.getCurrent().access(() -> {
homeView.refreshGrid();
LOG.info("The grid has been refreshed Automatically");
});
try {
getInstance().scheduleWithFixedDelay(task, INITIAL_DELAY, DELAY, TimeUnit.SECONDS);
} catch (Exception e) {
LOG.error("error" + e);
}
}
public final static ScheduledExecutorService getInstance() {
return instance;
}
}
答案 0 :(得分:2)
安排操作时,如果发生异常,则不会收到反馈。相反,它将停止执行它:
ScheduledExecutorService.scheduleWithFixedDelay(…)
:
...如果任务的任何执行遇到异常,则后续执行被禁止。
因此,您必须在操作本身中使用try … catch
块来报告,例如在lambda表达式中定义Runnable
:
Runnable task = () -> {
try { UI.getCurrent().access(…); }
catch (Exception e) { LOG.error("error" + e); }
};
我从一个非UI线程调用UI.getCurrent()
看起来很可疑,我怀疑它在尝试调用方法时返回null
导致NullPointerException
。< / p>