Spring中使用定时任务之Spring Task

关于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.xsd

2、开启定时器配置:

<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 * * ?")表示每天的2230分准时执行一次


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值