本文主要是介绍普通Java工程利用注解Spring做周期性任务调度框架搭建,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
需求:
利用注解Spring做周期任务执行操作,这样如果利用spring的task去操作那么会非常简单。
实现:
lib依赖:
<dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>3.2.0.RELEASE</version> </dependency> <dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>3.2.0.RELEASE</version> </dependency> <dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>3.2.0.RELEASE</version> </dependency>
spring配置文件:spring- collect.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"xmlns:beans="http://www.springframework.org/schema/beans" xmlns:device="http://www.springframework.org/schema/mobile/device"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd "><context:component-scan base-package="org.apache.tools.collect" /><bean id="propertyConfigure"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" /><task:scheduled-tasks><task:scheduled ref="preJob" method="run" cron="0 */1 * * * ?" /></task:scheduled-tasks> </beans>
main方法加载部分:
import org.springframework.context.support.ClassPathXmlApplicationContext;public class App {private static ClassPathXmlApplicationContext context = null;public static ClassPathXmlApplicationContext getContextInstance() {if (context == null) {start();}if (!context.isRunning()) {App.context.refresh();context.registerShutdownHook();}return context;}private static void start() {context = new ClassPathXmlApplicationContext("classpath:spring-collect.xml");context.registerShutdownHook();}public static void main(String[] args) {App.start();}
}
业务调度执行部分:
import org.springframework.stereotype.Service;@Service("preJob")
public class PreJob {public void run() {System.out.println("task execute**********"+System.currentTimeMillis());}
}
这篇关于普通Java工程利用注解Spring做周期性任务调度框架搭建的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!