SpringBoot幾種定時(shí)任務(wù)的實(shí)現(xiàn)方式

定時(shí)任務(wù)實(shí)現(xiàn)的幾種方式

  • Timer:這是java自帶的java.util.Timer類,這個(gè)類允許你調(diào)度一個(gè)java.util.TimerTask任務(wù)。使用這種方式可以讓你的程序按照某一個(gè)頻度執(zhí)行,但不能在指定時(shí)間運(yùn)行。一般用的較少。
  • ScheduledExecutorService:也jdk自帶的一個(gè)類;是基于線程池設(shè)計(jì)的定時(shí)任務(wù)類,每個(gè)調(diào)度任務(wù)都會(huì)分配到線程池中的一個(gè)線程去執(zhí)行,也就是說,任務(wù)是并發(fā)執(zhí)行,互不影響。
  • Spring Task:Spring3.0以后自帶的task,可以將它看成一個(gè)輕量級(jí)的Quartz,而且使用起來比Quartz簡(jiǎn)單許多。
  • Quartz:這是一個(gè)功能比較強(qiáng)大的的調(diào)度器,可以讓你的程序在指定時(shí)間執(zhí)行,也可以按照某一個(gè)頻度執(zhí)行,配置起來稍顯復(fù)雜。

使用spring task方法實(shí)現(xiàn)定時(shí)發(fā)送簡(jiǎn)單郵件

  • 首先配置QQ郵箱->設(shè)置->賬戶->開啟服務(wù)POP3/SMTP開啟->獲取授權(quán)碼

    image

在SpringBoot項(xiàng)目中,使用注解來實(shí)現(xiàn)定時(shí)任務(wù),首先創(chuàng)建項(xiàng)目,導(dǎo)入依賴:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

配置application.properties

spring.mail.host=smtp.qq.com
spring.mail.username=*******@qq.com
spring.mail.password=amujxrblfdyobeeh
spring.mail.default-encoding=UTF-8

如果不加下面3句,會(huì)報(bào)530錯(cuò)誤

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

MailService接口

public interface MailService {
/**
* 發(fā)送簡(jiǎn)單郵件
*/
void sendMail(String to,String subject,String content);

}

實(shí)現(xiàn)接口
@Service("mailService")
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender mailSender;

@Override
public void sendMail(String to, String subject, String content) {
    SimpleMailMessage mailMessage=new SimpleMailMessage();
    mailMessage.setFrom("******@qq.com");//發(fā)起者
    mailMessage.setTo(to);//接受者
    mailMessage.setSubject(subject);
    mailMessage.setText(content);
    try {
        mailSender.send(mailMessage);
        System.out.println("發(fā)送簡(jiǎn)單郵件");
    }catch (Exception e){
        System.out.println("發(fā)送簡(jiǎn)單郵件失敗");
    }
}


}

寫定時(shí)任務(wù):定時(shí)發(fā)送文件: 每天上午10:15觸發(fā)

@Service
//@Async
public class TaskService {
@Autowired
private MailService mailService;

@Scheduled(cron = "0 15 10 ? * *")
public void proces(){
    mailService.sendMail("815835155@qq.com","簡(jiǎn)單郵件","lalalalalalalaal");
    System.out.println("111");
}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容