springboot添加定时任务
- 首先,需要添加注解,@EnableScheduling
@SpringBootApplication @EnableScheduling public class SpringbootVueLearningApplication { public static void main(String[] args) { SpringApplication.run(SpringbootVueLearningApplication.class, args); } }
-
其次,添加注解 @Service将类注入到springboot容器中,托管给springboot管理,并且添加注解 @Scheduled,添加定时时长
@Service public class ImgSpiderImpl implements ImgSpider { //从0秒开始,每五秒执行一次; @Scheduled(cron = "0/5 * * * * *") @Override public void spider() throws IOException { String url = "https://pic.netbian.com/"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); CloseableHttpResponse response = httpClient.execute(httpPost); System.out.println(response); } }
cron 语法可以自行百度,具体可以参考:传送门