了解Springboot中的Cron,以自动发送电子邮件

时间:2019-01-11 19:30:46

标签: java spring-boot cron scheduled-tasks

关于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;
	}

}

1 个答案:

答案 0 :(得分: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开始

  

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

这样做没有什么害处,如果这不起作用,那么您就缺少了一些东西

@EnableScheduling 它将仅启用该功能

  

启用Spring的计划任务执行功能

@计划的

  

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