使用@scheduled注解在spring boot中调度函数

8ftvxx2r  于 2021-07-16  发布在  Java
关注(0)|答案(1)|浏览(330)

我想在我的Angular 表上指定的日期和时间执行以下方法-以下是输入:

<input required [(ngModel)]="emailNotification.sendingDate" class="form-control" type="datetime-local" name="sendingDate" id="time">

发送电子邮件的方法(从控制器)

@PostMapping(value="/getdetails")
    public @ResponseBody void sendMail(@RequestBody EmailNotification details) throws Exception {
        try {
            JavaMailSenderImpl jms = (JavaMailSenderImpl) sender;
            MimeMessage message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, StandardCharsets.UTF_8.name());

            helper.setFrom("smsender4@gmail.com");
            List<String> recipients = fileRepo.findWantedEmails(details.getDaysNum());
            String[] to = recipients.stream().toArray(String[]::new);
            helper.setTo(to);
            helper.setText(details.getMessage(),true);
            helper.setSubject("Test Mail");
            details.setRecipients(to);
            sender.send(message);
            enr.save(new EmailNotification(details.getId(), "Test mail", details.getMessage(), details.getDaysNum(), details.getRecipients(), details.getSendingDate()));
        } catch (MessagingException e) {
            throw new RuntimeException("fail to send emails: " + e.getMessage());
        }

电子邮件通知.class

public class EmailNotification {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String subject;
    private String message;
    private int daysNum;
    private String[] recipients;
    /*
     * @Temporal(TemporalType.TIMESTAMP)
     */ 
    //"yyyy-MM-dd'T'HH:mm:ss.SSSX"
    @Column(name = "sending_date")
    @Basic(fetch = FetchType.EAGER)
    private LocalDateTime sendingDate;

    public EmailNotification(long id, String subject,String message, int daysNum, String[] recipients, LocalDateTime sendingDate) {
        super();
        this.sendingDate = sendingDate;
        this.daysNum = daysNum;
        this.id = id;
        this.message = message;
        this.subject = subject;
    }

我不知道该怎么办,我ù如果有人帮忙,我会非常感激的

qnyhuwrf

qnyhuwrf1#

现在我想我明白你想达到什么目的了,所以检查一下这是否对你有效。
假设你想发送一封电子邮件时,在给定的表(我将命名为付款),有5天的最后期限。假设此表有一个名为payment的等效实体类,您可以执行以下操作:
如果支付实体有自己的crudepository扩展,您可以使用它来访问dabatase,那么您可以进行查询以查找接近截止日期的支付。这当然取决于您访问数据库的方式。下一个示例查询可能不起作用(因为据我所知,jpa不支持datediff),但可以作为您试图实现的目标的基础

@Repository
public interface PaymentRepository extends CrudRepository<Payment, Integer> {

    /* You need to find every payment that's 5 days from the deadline */
    @Query("SELECT p FROM PAYMENT p WHERE DATEDIFF(day, CURRENT_TIMESTAMP, p.deadline) <= 5")
    public List<PaymentRepository> findPaymentsCloseToDeadline();

}

创建一个计划任务类,在截止日期前为每一笔付款发送电子邮件。不要将参数传递给方法,而是使用您已经拥有的数据库访问权限来填充您的电子邮件。你不应该依赖前面收到的信息(比如Angular ),因为它很容易操作。使用你知道的信息,数据库中存储的信息。在本例中,任务从10:00开始:

@Configuration
@EnableScheduling
public class EmailScheduler {

    @Autowired
    private PaymentRepository paymentRepository;

    @Scheduled(cron = "0 0 10 * * ?")
    public void sendEmails() {
        JavaMailSenderImpl jms = (JavaMailSenderImpl) sender;
        MimeMessage message = jms.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, StandardCharsets.UTF_8.name());

        // Here you are accessing the payments close to the deadline
        List<Payment> payments = paymentRepository.findPaymentsCloseToDeadline();

        /* Send an email for each payment. Use the database info you already have to fill the information */
        for (Payment payment : payments) {
            try {
                helper.setFrom("smsender4@gmail.com");
                // Fill the recipients with the info you need
                String[] recipients = {payment.getUserEmail(), "other@email.com"};
                helper.setTo(recipients);
                String msg = "Here would go the message";
                helper.setText(msg, true);
                helper.setSubject("Test Mail");
                sender.send(message);
                // You would still need to calculate the ID and the days if you require them
                enr.save(new EmailNotification(id, "Test mail", msg, days,
                        recipients, "today's date in LocalDate"));
            } catch (MessagingException e) {
                throw new RuntimeException("fail to send emails: " + e.getMessage());
            }
        }
    }

}

这只是一个指导方针,因为关于你的代码还有一些我不知道的地方,但我希望它足够清楚,这样对你有帮助。祝你好运。

相关问题