如何启动将在java中按顺序运行的三个任务?

时间:2017-02-09 11:35:56

标签: java multithreading concurrency

我正在尝试启动三项任务:第一项将阅读一些电子邮件,在完成一项服务后,会根据这些电子邮件生成一些图表,最后这些图表将作为zip文件发送到电子邮件中。 这些任务必须按照这个精确的顺序运行:

dataReader - > graphGenerator - > emailSender。

我实现了这项服务,但我不明白为什么它不起作用。

@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;
    }
}

如果有更好的方法,请告诉我,谢谢!

2 个答案:

答案 0 :(得分:5)

这里有一些导致相同行为的代码:
简化,完美有序,但没有错误处理。

UserModel.update(
    SomeFindCriteria,
   { $inc: { timeSaved: newTimeSaved, moneySaved: newMoneySaved } }
)

答案 1 :(得分:2)

您还可以阅读有关CompletableFuture的更多信息,因为它更有用,更易于维护。然后阅读ExecutorService,因为恕我直言的好选项是预定义的线程数。

示例:

final ExecutorService executorService = Executors.newFixedThreadPool(1);

new CompletableFuture<String>().supplyAsync(() ->  dataReader.readWeeklyEmails(), executorService);

方法示例:

private String readWeeklyEmails(){
    return "";
}

如果您编写类似的代码,您可以轻松地控制任务和可能的异常