異步任務
註解:@Async,@EnableAsync
我新建一個Service,就叫AsyncService
package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("處理數據中...");
}
}
我線程休眠了5秒,再看看我的Controller
package com.example.controller;
import com.example.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello (){
asyncService.hello();
return "hello 許嵩";
}
}
運行一下,訪問http://localhost:8080/hello,要等待5秒纔會有結果啊,我不想等怎麼辦?使用異步任務。在Service方法上加一個@Async註解,在Mainapplication主方法上加上@EnableAsync開啓異步註解
@EnableAsync
public class MainApplication {...
@Async
public void hello(){...
然後重啓項目,你會發現,可以瞬間訪問了。
定時任務
註解:@Scheduled,@EnableScheduling
新建一個Service,叫ScheduleService,我直接在MainApplication加上@EnableScheduling註解了
package com.example.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledService {
@Scheduled(cron = "* * * * * MON-SAT")
public void hello(){
System.out.println("許嵩");
}
}
運行,發現控制檯每一秒都會打印出許嵩,這裏講解一下,更多的自己去查
cron=秒 分 時 日 月 周幾
*是所有,枚舉用逗號,時區用-,間隔是/
@Scheduled(cron = "* * * * * MON-SAT")//週一到週六,每秒執行一次
@Scheduled(cron = "0 * * * * MON-SAT")//0秒執行
@Scheduled(cron = "0,1,2,3 * * * * MON-SAT")//0至3秒的時候執行
@Scheduled(cron = "0-3 * * * * MON-SAT")//0至3秒執行
@Scheduled(cron = "0/3 * * * * MON-SAT")//每隔3秒執行