25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 13 ■ Adding E-mail and Scheduling Tasks<br />

@Test<br />

public void testEmail() throws InterruptedException{<br />

log.debug("Testing Email...");<br />

assertNotNull(email);<br />

}<br />

long start = new Date().getTime();<br />

email.send("user@gmail.com", "user@gmail.com", "New Document Add",<br />

"A new document was added to the collection.");<br />

long end = new Date().getTime();<br />

long time = (end - start)/1000;<br />

log.debug("Sending email done. Took: " + time + " seconds.");<br />

}<br />

Listing 13-4 shows the start and end time that will be use to calculate how long it takes to send an e-mail to the<br />

server. After running the unit test with<br />

gradle :ch13:test<br />

you should see something similar to the following output:<br />

2014-03-19 21:29:28,567 DEBUG [main] Testing Email...<br />

2014-03-19 21:29:38,147 DEBUG [main] Sending email done. Took: 10 seconds.<br />

■ ■Note If by some reason you get some errors, review the server, port, password, and other e-mail settings that go<br />

with your e-mail server provider.<br />

You have just sent an e-mail and it took 10 seconds (in this example) to do so. Now, let’s imagine that you have<br />

1,000 subscribers, and they want an e-mail per document, and you have 1,000 documents. It would take forever to<br />

send all those e-mails to your subscribers! There must be a better way to do this. Of course the <strong>Spring</strong> <strong>Framework</strong><br />

provides some nice features for this. Let’s see how in the next section.<br />

Let’s Talk About Asynchronous Tasks<br />

The <strong>Spring</strong> <strong>Framework</strong> provides an annotation called @Async to call methods asynchronously using the Tasks and<br />

Scheduling classes. These classes are a great way to solve the problem of sending many e-mails and waiting too long<br />

to get a response for every message sent. Let’s review Listing 13-5, the EmailService and its modification.<br />

Listing 13-5. EmailService.java<br />

package com.apress.isf.spring.email;<br />

import org.springframework.beans.factory.annotation.Autowired;<br />

import org.springframework.mail.MailSender;<br />

import org.springframework.mail.SimpleMailMessage;<br />

import org.springframework.scheduling.annotation.Async;<br />

import org.springframework.stereotype.Service;<br />

186

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!