SpringBoot配置定時任務的兩種方式
阿新 • • 發佈:2019-01-09
一、匯入相關的jar包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
二、啟動類啟用定時
在啟動類上面加上 @EnableScheduling 即可開啟定時
@SpringBootApplication @EnableScheduling public class Application {public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
三、建立定時任務實現類
第1種實現方式:
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class Scheduler1Task { private intcount = 0; @Scheduled(cron = "*/6 * * * * ?")/*每隔六秒鐘執行一次*/ private void process() { System.out.println("this is scheduler task runing " + (count++)); } }
第2種實現方式:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class Scheduler2Task { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Autowired private JavaMailSender mailSender; /* * @Scheduled(fixedRate = 6000) 上一次開始執行時間點之後6秒再執行 * @Scheduled(fixedDelay = 6000) 上一次執行完畢時間之後6秒再執行 * @Scheduled(initialDelay=1000, fixedRate=6000) 第一次延遲1秒後執行,之後按fixedRate的規則執行 * */ @Scheduled(fixedRate = 6000)/*每隔六秒鐘執行一次*/ public void reportCurrentTime() { System.out.println("現在時間:" + dateFormat.format(new Date())); SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("[email protected]"); message.setTo("[email protected]"); message.setSubject("主題:簡單郵件1"); message.setText("測試郵件內容1"); mailSender.send(message); } }