简体   繁体   English

计划的执行者服务不工作

[英]Scheduled Executor Service isn't working

I want a specific task to run everyday (every 24 hours).我希望每天(每 24 小时)运行一个特定任务。 I used a scheduled executor service but after I tested it with 20 seconds to see if the task would run, it didn't.我使用了计划的执行程序服务,但在我用 20 秒测试它以查看任务是否会运行后,它没有。 Am I doing something wrong?难道我做错了什么? Any help would be greatly appreciated.任何帮助将不胜感激。

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);

As @JeremeyFarrell said, use a Runnable instead of a TimerTask ; 正如@JeremeyFarrell所说,使用Runnable而不是TimerTask ; there is no functionality or benefit to be gained from using a TimerTask . 使用TimerTask没有任何功能或好处。

I've simplified your code and it just works without problems: 我已经简化了你的代码,它只是没有问题的工作:

ScheduledExecutorService scheduler = Executors
        .newScheduledThreadPool(1);

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

The most likely cause of your problem can be found in the Javadoc of scheduleWithFixedDelay : 您可能在scheduleWithFixedDelay的Javadoc中找到问题的最可能原因:

If any execution of the task encounters an exception , subsequent executions are suppressed. 如果任务的任何执行遇到异常 ,则后续执行被禁止。

You probably had an exception, possibly a RuntimeException (such as a NullPointerException ), which stopped further invocations. 您可能有一个异常,可能是RuntimeException (例如NullPointerException ),它停止了进一步的调用。

One way to solve that is to catch all exceptions and log them. 解决这个问题的一种方法是捕获所有异常并记录它们。

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);

(Note: of course, replace 1, TimeUnit.SECONDS with 24, TimeUnit.HOURS once you are satisfied that things work as expected) (注意:当然,一旦你对事情按预期工作,请将1, TimeUnit.SECONDS替换为24, TimeUnit.HOURS

A few things to point out: 有几点需要指出:

  • You're calling JOptionPane.showMessageDialog from a Thread that is not the UI thread. 您正在从不是UI线程的Thread调用JOptionPane.showMessageDialog Swing doesn't support doing UI work from any thread except the main UI thread; Swing不支持从主UI线程以外的任何线程执行UI工作; if you still do, you can get all kinds of race conditions. 如果你仍然这样做,你可以获得各种竞争条件。
  • In any case, even if that wasn't a problem, you're blocking your scheduled thread on user interaction; 在任何情况下,即使这不是问题,你也会阻止用户交互的预定线程; someone has to press "OK" before you application can continue 在您继续申请之前,有人必须按“确定”
  • But this doesn't cause your problem. 但这不会导致您的问题。

It is possible an exception occurs within the Task or also Runnable. Task 或 Runnable 中可能发生异常。 You will not recognize it.你不会认出它。 Try to implement something very simple first.首先尝试实现一些非常简单的东西。 Like a System.out.println("hello world").就像 System.out.println("hello world")。 Once this runs, work your way up to a more complex implementation.一旦运行,就可以逐步实现更复杂的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM