计划的执行程序服务无法正常工作

时间:2015-01-18 05:04:29

标签: java scheduled-tasks

我希望每天(每24小时)运行一项特定任务。我使用了一个预定的执行程序服务,但是在我用20秒测试它以查看任务是否会运行之后,它没有。难道我做错了什么? 任何帮助将不胜感激。

ScheduledExecutorService scheduler = Executors
            .newScheduledThreadPool(1);

    scheduler.scheduleWithFixedDelay(new TimerTask() {
        public void run() {
            ArrayList<Integer> people = new ArrayList<Integer>();
            try {
                shelf.g.setOverdue();
                for (int i = 1; i < 1000; i++) {
                    if (shelf.book[i] != null
                            && shelf.book[i].checkedOut != null) {
                        if (shelf.book[i].overdue == true) {
                            for (int i2 = 0; i < 600; i++) {
                                if (account.person[i] == null) {
                                    account.person[i] = new account();
                                }
                                if (account.person[i2].name
                                        .equalsIgnoreCase(shelf.book[i].personName)) {
                                    people.add(i2);
                                }
                            }
                        }
                    }
                }
                Set<Integer> s = new LinkedHashSet<Integer>(people);
                people = new ArrayList<Integer>(s);
                ArrayList<String> books = new ArrayList<String>();

                Properties props = new Properties();
                Session session = Session.getInstance(props);
                MimeMessage msg = new MimeMessage(session);
                Transport t = null;
                Address from = new InternetAddress(
                        "LGCCLibrary42@gmail.com", "LGCC Library");
                for (int i = 0; i < people.size(); i++) {
                    for (int i2 = 1; i2 < 1000; i2++) {
                        if (shelf.book[i2] != null
                                && shelf.book[i2].checkedOut != null) {
                            if (shelf.book[i2].overdue == true) {
                                if (account.person[people.get(i)].name
                                        .equalsIgnoreCase(shelf.book[i2].personName)) {

                                    books.add("Book " + i2 + " - " + shelf.book[i2].bookName
                                            + "\n");

                                }
                            }
                        }
                    }
                    String thePerson = account.person[people.get(i)].name;
                    Address to = new InternetAddress(account.person[people
                            .get(i)].eMail);

                    msg.setText(thePerson
                            + " , you have the following books overdue"
                            + "\n" + books.toString().replace("[", "").replace("]", ""));
                    msg.setFrom(from);
                    msg.setRecipient(Message.RecipientType.TO, to);
                    msg.setSubject("LGCC library overdue books");

                    t = session.getTransport("smtps");
                    t.connect("smtp.gmail.com", "LGCCLibrary42", "4JesusChrist");
                    t.sendMessage(msg, msg.getAllRecipients());
                    books.clear();
                }
                t.close();

            } catch (UnsupportedEncodingException ex) {
                // TODO Auto-generated catch block
                JOptionPane.showMessageDialog(null, "Something went wrong",
                        "Alert", JOptionPane.ERROR_MESSAGE);


            } catch (AddressException ex) {
                // TODO Auto-generated catch block
                JOptionPane.showMessageDialog(null, "Something went wrong",
                        "Alert", JOptionPane.ERROR_MESSAGE);

            } catch (MessagingException ex) {
                // TODO Auto-generated catch block
                JOptionPane.showMessageDialog(null, "Something went wrong",
                        "Alert", JOptionPane.ERROR_MESSAGE);

            }
        }
    }, 0, 24, TimeUnit.HOURS);

1 个答案:

答案 0 :(得分:9)

正如@JeremeyFarrell所说,使用Runnable代替TimerTask;使用TimerTask无法获得任何功能或好处。

我已经简化了您的代码,它可以毫无问题地运行:

ScheduledExecutorService scheduler = Executors
        .newScheduledThreadPool(1);

scheduler.scheduleWithFixedDelay(new Runnable() {
    public void run() {
        System.out.println("Do something useful");
    }
}, 0, 1, TimeUnit.SECONDS);

问题的最可能原因可以在scheduleWithFixedDelay的Javadoc中找到:

  

如果任务的任何执行遇到异常,则后续   执行被压制。

您可能有一个例外,可能是RuntimeException(例如NullPointerException),它会停止进一步的调用。

解决这个问题的一种方法是捕获所有异常并记录它们。

scheduler.scheduleWithFixedDelay(new Runnable() {
    public void run() {
        try {
            doTheRealWork(); // Such as "sendEmail()"
        } catch (Exception e) {
            e.printStackTrace(); // Or better, use next line if you have configured a logger:
            logger.error("Exception in scheduled e-mail task", e);
        }
    }
}, 0, 1, TimeUnit.SECONDS);

(注意:当您确信事情按预期工作时,请将1, TimeUnit.SECONDS替换为24, TimeUnit.HOURS

要指出的一些事项:

  • 您从非线程的线程调用JOptionPane.showMessageDialog。 Swing不支持从主UI线程以外的任何线程进行UI工作;如果你仍然这样做,你可以获得各种竞争条件。
  • 在任何情况下,即使这不是问题,您也会在用户互动时阻止您的预定线程;有人必须按&#34; OK&#34;在你的申请可以继续之前
  • 但这并不会导致您的问题。