首页 > 解决方案 > 了解 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.java 文件中放置 Enable Scheduling 注释的地方

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

}

标签: javaspring-bootcronscheduled-tasks

解决方案


了解cron表达式,它由六个字段组成。<year> field is optional. 文档

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

*方法all

?方法any

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

你是 cron 表达式很好,它会从10:15 AM每个月的第 15 天开始

将这两种方法结合起来是否正确?

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

@EnableScheduling它只会启用该功能

启用 Spring 的定时任务执行能力

@预定

标记要调度的方法的注释。必须指定 cron()、fixedDelay() 或 fixedRate() 属性之一。


推荐阅读