一.概述: 1.定时任务作为一种常见的需求,在java开发定时任务主要有三种解决方案: -JDK的timer -第三方组件: Quartz -Spring Task 2.Timer是jdk自带的定时任务工具,对于复杂的定时规则无法满足,在实际项目中也不常用; Quartz功能强大,但使用相对笨重。 Spring Task 则具备两者的优点,除相关的Spring包以外,不需要额外的包,支持注解和配置文件两种形式。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="com.vodka" />
<task:scheduled-tasks>
<task:scheduled ref="taskTest" method="jobOne" cron="0/2 * * * * ?"></task:scheduled>
</task:scheduled-tasks>
</beans>
<task:annotation-driven></task:annotation-driven>
XML配置scheduled
@Component
public class TaskTest {
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void jobOne(){
System.out.println("Happy birthday on " + simpleDateFormat.format(new Date()));
}
}
注解配置
@Component
public class TaskTest {
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Scheduled(cron = "1/5 * * * * ?")
public void jobOne(){
System.out.println("Happy birthday on " + simpleDateFormat.format(new Date()));
}
}
|