一、定時任務簡介
程序中設置定時任務的作用就是定時的執行某一任務,比如
- 管理系統定時向用戶發送短信、郵件等
- 互聯網金融項目定期批款,放款等操作
- 天氣預報系統定期更新數據
二、Spring Boot定時任務的使用
Spring Boot定時任務與Quartz定時任務的區別!
SpringBoot中使用定時任務非常簡單使用@EnableScheduling、@Scheduled註解即可!
操作步驟如下:
1.創建一個SpringBoot Web應用
2.@EnableScheduling開啓定時任務
@SpringBootApplication
@EnableScheduling //開啓定時任務
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
2.@Scheduled設置定時觸發執行的時間
@Scheduled的屬性
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
String cron() default "";
String zone() default "";
//@Scheduled(fixedDelay = 6000) :上一次執行完畢時間點之後6秒再執行
long fixedDelay() default -1;
String fixedDelayString() default "";
//比如:@Scheduled(fixedRate = 6000) :上一次開始執行時間點之後6秒再執行
long fixedRate() default -1;
String fixedRateString() default "";
//@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲1秒後執行,之後按fixedRate的規則每6秒執行一次
long initialDelay() default -1;
String initialDelayString() default "";
}
3.定時任務類必須注入spring容器,否則定時任務無效!
cron表達時的寫法:
常用的cron表達式含義
每隔5秒執行一次:*/5 * * * * ?
每隔1分鐘執行一次:0 */1 * * * ?
每天23點執行一次:0 0 23 * * ?
每天凌晨1點執行一次:0 0 1 * * ?
每月1號凌晨1點執行一次:0 0 1 1 * ?
每月最後一天23點執行一次:0 0 23 L * ?
每週星期天凌晨1點實行一次:0 0 1 ? * L
在26分、29分、33分執行一次:0 26,29,33 * * * ?
每天的0點、13點、18點、21點都執行一次:0 0 0,13,18,21 * * ?
@Service //必須向spring容器中註冊,否則定時任務無效!
public class TaskService {
//@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")//表示前4秒都執行一次
//@Scheduled(cron = "0-4 * * * * MON-SAT")//表示前4秒都執行一次
@Scheduled(cron = "0/4 * * * * MON-SAT") //表示每隔4秒執行一次
public void test01(){
System.out.println("=====定時執行一些業務=====");
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("hh:mm:ss");
System.out.println("當前時間:"+simpleDateFormat.format(new Date()));
System.out.println("01.定時向用戶發送短信");
System.out.println("02.定時刪除緩存中的數據");
System.out.println("03.定時數據庫備份");
}
//每隔6秒執行一次
@Scheduled(fixedRate = 6000)
public void test02(){
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("hh:mm:ss");
System.out.println("當前時間:"+simpleDateFormat.format(new Date()));
}
}
三、Spring Boot異步任務的使用
異步任務的作用:減少程序運行時間、提升系統響應速度、快速響應用戶!
SpringBoot異步處理使用場景
- 發送短信
- 發送郵件
- APP消息推送
- 節省運維凌晨發佈任務時間提供效率
SpringBoot異步任務使用步驟如下:
1.使用註解@EnableAsync開啓異步,會自動掃描
@EnableAsync //開啓異步處理開關
@SpringBootApplication
public class SpringbootAsyncApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAsyncApplication.class, args);
}
}
2.定義@Component、@Async作爲組件被容器掃描並且執行
@Component
public class AsyncTask {
/**
* 1.如果執行下面三個方法是同步任務耗時:1000+800+400
* 2.開啓異步任務執行下面三個方法耗時:取耗時最大的1000,
* 也就是執行三個方法只需要1000
*/
@Async
public Future<Boolean> doTask01()throws Exception{
long start=System.currentTimeMillis();
//使用線程的目的測試方法執行時間
Thread.sleep(1000);
long end=System.currentTimeMillis();
System.out.println("執行任務1耗時:"+(end - start)+"毫秒");
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> doTask02()throws Exception{
long start=System.currentTimeMillis();
Thread.sleep(700);
long end=System.currentTimeMillis();
System.out.println("執行任務2耗時:"+(end - start)+"毫秒");
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> doTask03()throws Exception{
long start=System.currentTimeMillis();
Thread.sleep(600);
long end=System.currentTimeMillis();
System.out.println("執行任務3耗時:"+(end - start)+"毫秒");
return new AsyncResult<>(true);
}
}
3.測試異步任務執行總時間
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootAsyncApplicationTests {
@Autowired
AsyncTask asyncTask;
@Test
public void test()throws Exception {
long start=System.currentTimeMillis();
Future<Boolean> f1=asyncTask.doTask01();
Future<Boolean> f2=asyncTask.doTask02();
Future<Boolean> f3=asyncTask.doTask03();
//執行此段代碼也需要耗時間
while(!f1.isDone()||!f2.isDone()||!f3.isDone()) {
if(f1.isDone() && f2.isDone() && f3.isDone())
break;
}
long end=System.currentTimeMillis();
System.out.println("執行以上三個任務總耗時:"+(end - start)+"毫秒");
}
}
4.執行三個方法總耗時
執行任務3耗時:601毫秒
執行任務2耗時:701毫秒
執行任務1耗時:1000毫秒
執行以上三個任務總耗時:1028毫秒
5.如果註釋@Async,那麼就是同步任務。三個任務執行總耗時=600+700+1000(毫秒)