关于Spring Task
Spring task,我们可以将它比作一个轻量级的Quartz,使用简单方便,除spring相关的包外不需要额外的包,我们一般用来实现定时任务。
Spring中整合spring task
1、在springmvc的配置文件springmvc.xml中配置timetask的命名空间
xmlns:task="http://www.springframework.org/schema/task"在xsi:schemaLocation中引入timetask的标签规范:
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd2、开启定时器配置:
<task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
<task:scheduler id="qbScheduler" pool-size="10"/> 编写spring task的相关代码
编写spring task相关代码:
@Component("taskJob")
public class TimeTask {
@Autowired
private AreaService areaService;
@Scheduled(cron="0 0 0-23 * * ?")
public void keepConnectToMysql(){
try {
areaService.findArea();
System.out.println(new Date().toString()+"数据库连接正常...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}@Scheduled(cron="0 0 0-23 * * ?")是一个cron表达式,用来表示定时器触发的时机。
关于cron表达式
格式为:{秒} {分} {时} {日期(具体哪天)} {月} {星期}
上面的表达式就表示0-23小时每隔一小时执行一次
@Scheduled(cron="0 30 22 * * ?")表示每天的22:30分准时执行一次
本文介绍如何在Spring框架中使用Spring Task实现定时任务,包括配置步骤与具体代码示例,展示了轻量级定时任务解决方案。
830

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



