Java EE: Scheduler


Enterprise newcomers often tend to use unnecessary libraries for simple tasks that are possible without. For many scheduling tasks in web applications, you don't need to use libraries like Quartz. Let's say that you want to send an mail every midnight:

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailService {
    @Resource(name = "mail/defaultMail")
    private Session mailSession;

    @Schedule(hour = "0", dayOfMonth = "*", persistent = false)
    public void scheduleMail() {
                                                          "Sending scheduled e-mail");
        sendMail("", "test", "test");

    public void sendMail(String recipient, String subject, String body) {
        try {
            MimeMessage message = new MimeMessage(mailSession);

            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            message.setText(body, "utf-8", "html");

        catch (MessagingException me) {
            Logger.getLogger(MailService.class.getName()).log(Level.SEVERE, null, me);

Only the @Schedule Annotation is required which can even be constructed programmatically. Read more about it in the official Java EE 7 Timer Service Tutorial.