前情提要
在进行开发的时候,通常我们需要设置一个定时的任务,比如定时清理应用缓存等,对于这种情况,我们可以在前端通过js创建定时任务发送http来实现,而这看起来却类似轮询了,并且随着使用时长的增加,发送的http请求也相应的增加。SpringBoot可以非常简单的实现这个功能
SpringBoot创建一个简单的定时任务
首先创建定时任务类:
package org.framework.demo.section1;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* 设置一个定时任务
* @author chengxi
*/
@Configuration
@EnableScheduling
public class ScheduleConfig {
@Scheduled(cron = "0/20 * * * * ?")
public void scheduler(){
System.out.println("执行了哟");
}
}
然后编写tomcat启动类:启动类测试代码这里就不贴了,前面的系列篇都有,都可以用于测试
然后启动tomcat启动类,查看控制台,就会发现每过20S都会输出执行了哟
,即表示定时任务创建成功