【问题标题】:java Scheduler is not workingjava调度程序不工作
【发布时间】:2015-08-06 13:36:14
【问题描述】:

我在 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 上的文件夹。

【问题讨论】:

  • 您是否在 web.xml 中或使用注解注册了监听器?为什么要从 runnable 的构造函数启动线程?
  • 我只是在尝试线程部分。应该删除它。我的错。您能否详细说明“注册”到 web.xml 的含义?
  • 你在看in the right logs吗?无论如何,我不建议使用System.out;使用适当的日志记录服务。
  • 仅仅因为您的应用程序中有一个实现 ServletContextListener 的类并不意味着 Tomcat 会找到并调用它。就像 servlet、过滤器等一样,监听器必须在 web.xml 中声明(或者使用 servlet 3.0 以后的注释)。使用谷歌了解如何。

标签: java tomcat scheduler


【解决方案1】:

为什么使用线程池来运行线程 你的代码:

private void StartUp() {
    System.out.println("start");
    (new Thread(this)).start();
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多