有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java理解Springboot中的Cron,自动发送电子邮件

关于Cron有很多信息,我有点困惑。大部分信息仅与设置定时cron注释有关。我以前从未使用过SpringBoot调度。我想做的是设置一封电子邮件每月发送一次,比如每个月的15号。在使用EmailService和Helpers之前,我已经发送过电子邮件。将这两种方法结合起来是正确的,还是应该设置电子邮件模板并以不同的方式发送电子邮件?我没有发送电子邮件(当我改为今天的日期和时间时)。有谁能告诉我为什么它没有在预定的时间发送,我是否遗漏了一些代码,或者这不是安排时间的方式吗?我以前使用过这种通过电子邮件服务发送电子邮件的方法,而且它是有效的,所以我设置调度程序的方式肯定有问题。有人知道为什么它没有在预定的时间运行sendReminder()吗

这是我目前代码中的内容。。。 控制器:

@Controller
public class MailController {
    @Autowired
    LicenseRepository licenseRepository;

    @Autowired
    InsuranceRepository insuranceRepository;

    @Autowired
    EmailService emailService;

    @Scheduled(cron = "0 15 10 15 * ?")
    public void sendReminder(){
        License license = new License();
        Insurance insurance = new Insurance();
        Mail mail = new Mail();
        mail.setFrom("no-reply@gmail.com");
        mail.setTo(new String[]{"myemail@gmail.com"});
        mail.setSubject("Policy Renewal Notice");

        Map<String, Object> mailModel = new HashMap<String, Object>();
        mail.setModel(mailModel);

        try {
            emailService.sendSimpleMessage(mail, license, insurance);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    @RequestMapping(value="/email")
    public String email(){
        return "emailMessage";
    }
}

以及电子邮件服务:

@Service
public class EmailService{

    private JavaMailSender javaMailSender;

    @Autowired
    public EmailService(JavaMailSender javaMailSender){
        this.javaMailSender = javaMailSender;
    }

    @Autowired
    private SpringTemplateEngine templateEngine;

    public void sendSimpleMessage(Mail mail, License license, Insurance insurance) throws MessagingException, IOException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,
                MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                StandardCharsets.UTF_8.name());

        helper.addAttachment("Mail_Icon.png", new ClassPathResource("static/images/Mail_Icon.png"));

        Context context = new Context();
        context.setVariables(mail.getModel());
        context.setVariable("license",license);
        context.setVariable("insurance",insurance);
        String html = templateEngine.process("emailMessage", context);

        helper.setTo(mail.getTo());
        helper.setText(html, true);
        helper.setSubject(mail.getSubject());
        helper.setFrom(mail.getFrom());

        javaMailSender.send(message);
    }



}

最后是html电子邮件模板:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>HTML Reminder Email</title>
    <style type="text/css">
  lots of styling here removed for easier reading
  </style>
</head>

<body bgcolor="#f6f8f1">
<table width="100%" bgcolor="#f6f8f1" border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td>
            <!--[if (gte mso 9)|(IE)]>
            <table width="600" align="center" cellpadding="0" cellspacing="0" border="0">
                <tr>
                    <td>
            <![endif]-->
            <table bgcolor="#ffffff" class="content" align="center" cellpadding="0" cellspacing="0" border="0">
                <tr>
                    <td bgcolor="#6435c9" class="header">
                        <table width="70" align="left" border="0" cellpadding="0" cellspacing="0">
                            <tr>
                                <td height="70" style="padding: 0 20px 20px 0;">
                                    <img class="fix" src="cid:Mail_Icon.png" width="70" height="70" border="0" alt="" />
                                </td>
                            </tr>
                        </table>
                        <!--[if (gte mso 9)|(IE)]>
                        <table width="425" align="left" cellpadding="0" cellspacing="0" border="0">
                            <tr>
                                <td>
                        <![endif]-->
                        <table class="col425" align="left" border="0" cellpadding="0" cellspacing="0" style="width: 100%; max-width: 425px;">
                            <tr>
                                <td height="70">
                                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                        <tr>
                                            <td class="subhead" style="padding: 0">
                                                Policy Renewal Expiration Reminder
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                        <!--[if (gte mso 9)|(IE)]>
                        </td>
                        </tr>
                        </table>
                        <![endif]-->
                    </td>
                </tr>
                <tr>
                    <td class="innerpadding borderbottom">
                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr class="emailRow">
                                <p>AFFILIATE NAME HERE</p>
                            </tr>
                            <tr class="emailRow">
                                <p>Our Records indicate that your policy is up for renewal in 30 days. Please provide the updated proof of insurance to the Director of Operations by email: <a href="mailto:myemail@gmail.com">myemail@gmail.com</a>.  We appreciate your compliance. </p>
                                <p>Thank you,</p>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</body>
</html>

这就是我在main中放置Enable Scheduling注释的地方。java文件

@EntityScan( basePackageClasses = {ODbApplication.class, Jsr310JpaConverters.class} ) @EnableScheduling @SpringBootApplication @Configuration public class ODbApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(ODbApplication.class); } public static void main(String[] args) { SpringApplication.run(ODbApplication.class, args); } @Bean public FilterRegistrationBean securityDatabaseFilterRegistration(SecurityDatabaseFilter securityDatabaseFilter) { FilterRegistrationBean registrationBean = new FilterRegistrationBean(securityDatabaseFilter); registrationBean.setEnabled(false); return registrationBean; } }

共 (1) 个答案

  1. # 1 楼答案

    理解cron表达式,它由六个字段组成<year> field is optional.docs

    <second> <minute> <hour> <day-of-month> <month> <day-of-week> <year>
    

    *表示all

    ?表示any

    @Scheduled(cron = "0 15 10 15 * ?")

    你知道cron表达式很好,它将在每个月15日的10:15 AM开始

    Is it right to combine these two methods ?

    这样做没有坏处,如果这样做不起作用,那么你就错过了一些东西

    @EnableScheduling它只会启用该功能

    Enables Spring's scheduled task execution capability

    @Scheduled

    An annotation that marks a method to be scheduled. Exactly one of the cron(), fixedDelay(), or fixedRate() attributes must be specified.