我在 java web 部署中使用以下代码作为调度程序
public class ReportScheduler implements ServletContextListener {
private ScheduledExecutorService scheduler;
@Override
public void contextInitialized(ServletContextEvent sce) {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new ReportLoader(sce.getServletContext()), 0, 10, TimeUnit.SECONDS);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
scheduler.shutdownNow();
}
实现runnable的ReportLoader类如下:
public class ReportLoader implements Runnable {
ServletContext context;
public ReportLoader(ServletContext context) {
System.out.println("1");
this.context = context;
StartUp();
}
private void StartUp() {
System.out.println("start");
(new Thread(this)).start();
}
@Override
public void run() {
System.out.println("scheduled");
try {
//Files.delete(path);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
但是我的调度程序似乎没有工作,因为没有像人们期望的那样在 tomcat(这是我的服务器)日志上打印任何内容。
我是否犯了任何错误,或者我需要确保调度程序正常工作的其他内容?
调度程序的目的是定期删除本地 PC 上的文件夹。
最佳答案
为什么要用线程池来运行一个Thread 你的代码:
private void StartUp() {
System.out.println("start");
(new Thread(this)).start();
}
关于java调度程序不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30432111/