今年开发的东西是C++的,但最近有个项目时间紧迫,临时又被拉去做java和web。记录一下使用springboot的定时器时的问题。
SpringBoot的定时任务非常简单,定时任务也不用整合quartz了,直接schedule就欧了。
1、引入POM依赖
Spring的Schedule包含在spring-boot-starter模块中,无需引入其他依赖。
2、开启注解支持
在启动类增加注解:@EnableScheduling
3、小例子
@Component
public class RuntimeDataSender {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Resource
private WebSocketServer webSocketServer;
@Autowired
private RuntimeDataController dataController;
List<String> runtimePointMridList = new ArrayList<String>();
@Scheduled(fixedRate=10000)
public void sendRuntimeDataByFixed() {
runtimePointMridList = RuntimeDataController.runtimePointMridList;
//System.out.println("timing tasks go: ");
if(runtimePointMridList!=null && runtimePointMridList.size()>0)
{
for(int i=0;i<runtimePointMridList.size();i++)
{
。。。。。。。。。。。省略
String messageStr = obj.toJSONString();
System.out.println("runtimeData go: "+messageStr);
webSocketServer.sendInfo("runtimeData", messageStr);
}
}
}
}
最后,重要提示,使用时要注意:
1、该定时任务实现的方法,是不可以有参数的。
2、该定时任务类中,其他方法不能有其他的@注解的使用,否则定时任务不执行。
我起初时,把这个定时的实现方法sendRuntimeDataByFixed()放在了controller类里面,因为该类中的其他很多方法使用时也添加了别的注解,导致,定时任务不生效。
本文介绍如何在SpringBoot中使用内置的Schedule定时任务,包括POM依赖引入、注解开启及示例代码分享,同时提醒注意事项,如定时任务方法不能有参数及避免与其他注解混用。
831

被折叠的 条评论
为什么被折叠?



