木头人
2016-11-14 14:44:14
spring3.x自带的任务调度的注解实现
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.stephen.spring.quartz.itask.IMyTask;
@Component
public class MyTask implements IMyTask{
/*每一秒执行一次*/
@Scheduled(cron="0/1 * * * * ? ")
public void sayHello() {
System.out.println("welcome my first quartz demo!");
}
}
通过注解,spring简化了spring+quartz的配置,使代码更简洁,更可读性强。从java自带的TimerTask到quartz,再到spring,到处可以看见任务调度的影子,下面介绍spring的作业调度。
1.spring的xml的配置:
<?xml version="1.0" encoding="UTF-8"?>
<!-- 查找最新的schemaLocation 访问 http://www.springframework.org/schema/ -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd ">
<context:component-scan base-package="com.stephen.spring"/>
<!-- 配置线程池 -->
<task:scheduler id="myScheduler" pool-size="5" />
<task:executor id="myExecutor" pool-size="5" />
<!-- 开启注解 -->
<task:annotation-driven scheduler="myScheduler" executor="myExecutor"/>
</beans>
2.定义自己的任务:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.stephen.spring.quartz.itask.IMyTask;
@Component
public class MyTask implements IMyTask{
/*每一秒执行一次*/
@Scheduled(cron="0/1 * * * * ? ")
public void sayHello() {
System.out.println("welcome my first quartz demo!");
}
}
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.stephen.spring.quartz.itask.IMyTask2;
@Component
public class MyTask2 implements IMyTask2{
public final static String pattern="yyyy-MM-dd HH:mm:ss";
/*使用注解时被注解的方法不能含有参数*/
@Scheduled(cron="0/5 * * * * ? ")
public void getCurrentDate() {
DateFormat dateFormat=new SimpleDateFormat(pattern);
String time=dateFormat.format(new Date().getTime());
System.out.println(time);
}
}
3.测试自己的任务调度:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestApp {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:spring/spring-quartz.xml");
}
}
4.测试的结果:
5.主要的配置就是这些了,不当之处敬请谅解指出
评论




最近浏览
