How do I start three tasks that will run sequentially in Java?
•
Java
I'm trying to start three tasks: the first one will read some emails, generate some charts based on these emails after completing a service, and start. Finally, these charts will be sent to the email as zip files
dataReader – > graphGenerator – > emailSender.
I implemented this service, but I don't understand why it doesn't work
@Component public class WeeklyEmailService { @Autowired private EmailSender emailSender; @Autowired private GraphGenerator graphGenerator; @Autowired private DataReader dataReader; @Autowired private CompanyRepository companyRepository; @Autowired private EmailConfigurer emailConfigurer; @Value("${mail.username}") private String username; @Value("${mail.password}") private String password; public void sendWeeklyEmail() { emailConfigurer.setUsername(username); emailConfigurer.setPassword(password); if (emailConfigurer.configure() != null) { System.out.println("Connection successfully established with mail server!"); } Task<Void> reader = new Task<Void>() { @Override protected Void call() throws Exception { dataReader.readWeeklyEmails(); return null; } }; Task<Void> generator = new Task<Void>() { @Override protected Void call() throws Exception { companyRepository.getCompanyNames().forEach(company -> { graphGenerator.generateGraphs(new DateTime().minusWeeks(1),new DateTime(),company); }); return null; } }; Task<Void> emailTask = new Task<Void>() { @Override protected Void call() throws Exception { emailSender.sendMailWithAttachment(); return null; } }; reader.setOnSucceeded(event -> { Thread generatorThread = new Thread(generator); generatorThread.start(); }); generator.setOnSucceeded(event -> { Thread emailThread = new Thread(emailTask); emailThread.start(); }); emailTask.setOnSucceeded(event -> { if (clean()) { System.out.println("Graphs Reports and ZIP files deleted from your computer"); } else { System.out.println("Files which you want to delete do not exists"); } }); Thread readerThread = new Thread(reader); readerThread.start(); } private boolean clean() { boolean cleaned = false; try { cleaned = Files.deleteIfExists(Paths.get("graphs")); cleaned = Files.deleteIfExists(Paths.get("reports")); cleaned = Files.deleteIfExists(Paths.get("zip")); } catch (IOException e) { e.printStackTrace(); } return cleaned; } }
If there is a better way, please tell me, thank you!
Solution
Here are some codes that cause the same behavior:
Thread sendWeeklyEmailThread = new Thread(new Runnable(){ public void run() { readWeeklyEmails(); generateGraphs(); sendMailWithAttachment(); clean(); //cleanup.... } }); sendWeeklyEmailThread.start();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码