Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduled Executor Service isn't working

I want a specific task to run everyday (every 24 hours). I used a scheduled executor service but after I tested it with 20 seconds to see if the task would run, it didn't. 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(
                        "[email protected]", "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);
like image 966
noobProgrammer Avatar asked Jan 18 '15 05:01

noobProgrammer


1 Answers

As @JeremeyFarrell said, use a Runnable instead of a TimerTask; there is no functionality or benefit to be gained from using a 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:

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.

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)

A few things to point out:

  • You're calling JOptionPane.showMessageDialog from a Thread that is not the UI thread. Swing doesn't support doing UI work from any thread except the main UI thread; 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.
like image 139
Erwin Bolwidt Avatar answered Oct 10 '22 22:10

Erwin Bolwidt