Spring Schedule:Spring boot整合Spring Schedule实战讲解定时发送邮件的功能
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import java.io.IOException;
@Service
public class EmailSchedulerService {
private final EmailService emailService;
public EmailSchedulerService(EmailService emailService) {
this.emailService = emailService;
}
// 每天凌晨1点执行
@Scheduled(cron = "0 0 1 * * ?")
public void scheduleEmailDelivery() throws IOException, MessagingException {
emailService.sendEmail("recipient@example.com", "Subject", "Email Content");
}
}
这段代码演示了如何使用Spring Schedule来定义一个计划任务,该任务会在每天凌晨1点执行,以自动发送电子邮件。这是一个简单的例子,展示了如何将定时任务集成到Spring Boot应用程序中。在实际应用中,你需要根据具体需求调整cron表达式和邮件内容。
评论已关闭