原创转载请注明出处:http://agilestyle.iteye.com/blog/2327299
Project Directory
Maven Dependency
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.fool</groupId> <artifactId>springschedule</artifactId> <name>springschedule</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> <org.springframework-version>4.2.8.RELEASE</org.springframework-version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.10.3.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.11.Final</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.21</version> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.3.4</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.9.4</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.3.11.v20160721</version> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <httpConnector> <port>8888</port> </httpConnector> <webApp> <contextPath>/springschedule</contextPath> </webApp> </configuration> </plugin> </plugins> </build> </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
root-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Root Context: defines shared resources visible to all other web components --> </beans>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <task:annotation-driven executor="myExecutor" scheduler="myScheduler" /> <task:executor id="myExecutor" pool-size="5" /> <task:scheduler id="myScheduler" pool-size="10" /> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <context:component-scan base-package="org.fool.springschedule" /> </beans:beans>
schema.sql
DROP TABLE IF EXISTS CAR; CREATE TABLE CAR ( ID INT NOT NULL AUTO_INCREMENT, LICENSE_PLATE VARCHAR(20) NOT NULL, MANUFACTURER VARCHAR(20) NOT NULL, MANUFACTURE_DATE DATE NOT NULL, AGE INT NOT NULL DEFAULT 0, VERSION INT NOT NULL DEFAULT 0, UNIQUE UQ_CAR_1 (LICENSE_PLATE), PRIMARY KEY (ID) ); insert into car (license_plate, manufacturer, manufacture_date) values ('LICENSE-1001', 'Ford', '1980-07-30'); insert into car (license_plate, manufacturer, manufacture_date) values ('LICENSE-1002', 'Toyota', '1992-12-30'); insert into car (license_plate, manufacturer, manufacture_date) values ('LICENSE-1003', 'BMW', '2003-1-6');
db.properties
#Database Configuration #jdbc.driver=org.hsqldb.jdbcDriver #jdbc.url=jdbc:hsqldb:mem:testdb;shutdown=false #jdbc.username=sa #jdbc.password= jdbc.databaseName=springdata jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/${jdbc.databaseName}?useUnicode=true&characterEncoding=UTF-8&useSSL=false jdbc.username=root jdbc.password=123456 #Hibernate Configuration hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.format_sql=true hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy hibernate.show_sql=false #hibernate.hbm2ddl.auto=create-drop
DALConfig.java
package org.fool.springschedule.config; import java.util.Properties; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @EnableJpaRepositories("org.fool.springschedule.repository") @PropertySource("classpath:META-INF/db.properties") @ComponentScan("org.fool.springschedule") public class DALConfig { @Value("${jdbc.driver}") private String jdbcDriver; @Value("${jdbc.url}") private String jdbcUrl; @Value("${jdbc.username}") private String jdbcUsername; @Value("${jdbc.password}") private String jdbcPassword; @Value("${hibernate.dialect}") private String hibernateDialect; @Value("${hibernate.format_sql}") private String hibernateFormatSql; @Value("${hibernate.ejb.naming_strategy}") private String hibernateEjbNamingStrategy; @Value("${hibernate.show_sql}") private String hibernateShowSql; @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfig() { return new PropertySourcesPlaceholderConfigurer(); } @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(jdbcDriver); dataSource.setUrl(jdbcUrl); dataSource.setUsername(jdbcUsername); dataSource.setPassword(jdbcPassword); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.dialect", hibernateDialect); jpaProperties.put("hibernate.format_sql", hibernateFormatSql); jpaProperties.put("hibernate.ejb.naming_strategy", hibernateEjbNamingStrategy); jpaProperties.put("hibernate.show_sql", hibernateShowSql); entityManagerFactoryBean.setJpaProperties(jpaProperties); entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setPackagesToScan("org.fool.springschedule.domain"); entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); return entityManagerFactoryBean; } @Bean public JpaTransactionManager transactionManager() throws ClassNotFoundException { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } }
Car.java
package org.fool.springschedule.domain; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Version; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @Entity @Table(name="car") public class Car { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") private Long id; @Column(name = "LICENSE_PLATE") private String licensePlate; @Column(name = "MANUFACTURER") private String manufacturer; @Column(name = "MANUFACTURE_DATE") private Date manufactureDate; @Column(name = "AGE") private int age; @Version private int version; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLicensePlate() { return licensePlate; } public void setLicensePlate(String licensePlate) { this.licensePlate = licensePlate; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public Date getManufactureDate() { return manufactureDate; } public void setManufactureDate(Date manufactureDate) { this.manufactureDate = manufactureDate; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
CarRepository.java
package org.fool.springschedule.repository; import org.fool.springschedule.domain.Car; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface CarRepository extends CrudRepository<Car, Long> { }
CarService.java
package org.fool.springschedule.service; import java.util.List; import org.fool.springschedule.domain.Car; public interface CarService { List<Car> findAll(); Car save(Car car); void updateCarAgeJob(); }
CarServiceImpl.java
package org.fool.springschedule.service.impl; import java.util.List; import javax.inject.Inject; import org.fool.springschedule.domain.Car; import org.fool.springschedule.repository.CarRepository; import org.fool.springschedule.service.CarService; import org.joda.time.DateTime; import org.joda.time.Years; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.Lists; @Service @Transactional public class CarServiceImpl implements CarService { private final Logger logger = LoggerFactory.getLogger(CarServiceImpl.class); @Inject private CarRepository carRepository; @Override @Transactional(readOnly = true) public List<Car> findAll() { return Lists.newArrayList(carRepository.findAll()); } @Override public Car save(Car car) { return carRepository.save(car); } @Override @Scheduled(fixedDelay = 10000) public void updateCarAgeJob() { List<Car> cars = findAll(); DateTime currentDate = DateTime.now(); logger.info("Car age update job started"); for (Car car : cars) { int age = Years.yearsBetween(new DateTime(car.getManufactureDate()), currentDate).getYears(); car.setAge(age); save(car); logger.info("Car age update--- " + car); } logger.info("Car age update job completed successfully"); } }
Test
SpringScheduleTest.java
package org.fool.springschedule.test; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringScheduleTest { public static void main(String[] args) { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml"); while (true) { } } }
run it
Asynchronous Task Execution in Spring
AsyncService.java
package org.fool.springschedule.service; import java.util.concurrent.Future; public interface AsyncService { void asyncTask(); Future<String> asyncWithReturn(String name); }
AsyncServiceImpl.java
package org.fool.springschedule.service.impl; import java.util.concurrent.Future; import org.fool.springschedule.service.AsyncService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Service; @Service public class AsyncServiceImpl implements AsyncService { private final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class); @Override @Async public void asyncTask() { logger.info("Start execution of async. task"); try { Thread.sleep(10000); } catch (Exception ex) { ex.printStackTrace(); } logger.info("Complete execution of async. task"); } @Override @Async public Future<String> asyncWithReturn(String name) { logger.info("Start execution of async. task with return"); try { Thread.sleep(5000); } catch (Exception ex) { ex.printStackTrace(); } logger.info("Complete execution of async. task with return"); return new AsyncResult<String>("Hello: " + name); } }
Test
SpringAsyncTest.java
package org.fool.springschedule.test; import java.util.concurrent.Future; import org.fool.springschedule.service.AsyncService; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringAsyncTest { public static void main(String[] args) { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml"); AsyncService asyncService = ctx.getBean(AsyncService.class); for (int i = 0; i < 5; i++) { asyncService.asyncTask(); } Future<String> result1 = asyncService.asyncWithReturn("Baidu"); Future<String> result2 = asyncService.asyncWithReturn("Alibaba"); Future<String> result3 = asyncService.asyncWithReturn("Tencent"); try { Thread.sleep(6000); System.out.println("Result1: " + result1.get()); System.out.println("Result2: " + result2.get()); System.out.println("Result3: " + result3.get()); } catch (Exception ex) { ex.printStackTrace(); } } }
run it
Reference
Apress.Pro Spring 4th Edition.2014 - CHAPTER 11 Task Scheduling in Spring
相关推荐
Spring提供了多种方式来实现定时任务,其中一种是使用`TaskScheduler`接口或者`@Scheduled`注解配合`TaskExecutor`。本实例将详细介绍如何在Spring中设置一个基于`cronExpression`表达式的定时任务。 首先,让我们...
本示例"spring_schedule_task_demo.rar"提供了一个关于如何使用Spring进行定时任务设置的演示,包括基于配置和基于注解两种方式。 首先,我们来讨论基于配置的方式。在Spring中,我们可以使用`*>` XML命名空间来...
这个"spring定时器简单的demo"应该包含了一个使用Spring Task实现简单定时任务的例子。 首先,Spring Task的配置通常在`applicationContext.xml`文件中进行。在这个配置文件中,我们需要启用Spring的Task执行器,这...
Spring Task提供了两种主要的方式来创建定时任务:`@Scheduled`注解和`TaskScheduler`接口。`@Scheduled`注解可以用于方法上,用于声明一个定时任务,而`TaskScheduler`接口则允许自定义任务调度逻辑。 ```java // ...
在Spring3中,通过引入注解`@Scheduled`,使得创建计划任务变得更加简单和直观。本文将详细介绍如何在Spring3中使用`@Scheduled`注解来创建计划任务。 首先,你需要创建一个Java类,该类中包含需要周期性执行的方法...
这个"spring定时任务demo包含jar包"提供了一个完整的示例,帮助我们快速理解和实现Spring定时任务。 在Spring中,定时任务的实现主要依赖于`Spring Task`模块,它提供了`@Scheduled`注解和`TaskScheduler`接口来...
在实际应用中,你可以根据需求调整 Job 和 Trigger 的配置,或者使用 Spring 的 `@Scheduled` 注解进行更简单的定时任务声明。 总结来说,"Quartz+spring定时任务demo" 提供了一个集成 Quartz 与 Spring 的实例,...
【Spring定时器Demo详解】 在Java开发中,Spring框架提供了强大的定时任务管理功能,通过`Spring Task`模块,我们可以方便地实现定时任务的设定和执行。这个“spring定时器demo”是一个完整的工作示例,涵盖了从...
对于定时调度,可以结合Spring的`@Scheduled`注解或Quartz等外部调度器。 通过这个"Spring Batch学习demo项目源码",你可以学习如何设置这些组件,观察它们如何协同工作完成批量处理任务。深入研究源码,理解每个...
在"Java Spring多线程demo代码"中,可能包含使用`@Async`和`@Scheduled`注解的示例,以及如何配置和自定义`ThreadPoolTaskExecutor`和`ThreadPoolTaskScheduler`的代码。通过这些示例,你可以学习到如何在Spring应用...
Spring通过`@Scheduled`注解提供了一种简单而强大的方式来执行定时任务。这个注解可以应用于方法上,指定任务的执行周期。例如,如果你想要每隔5秒钟执行一次某个方法,你可以这样写: ```java import org.spring...
在这个"基于Spring的Quartz Demo"中,我们将探讨如何在Spring环境中配置和使用Quartz。以下是一些关键的知识点: 1. **Quartz配置**: - 首先,你需要在项目的类路径下放置`quartz.properties`配置文件,设置...
这个"spring定时任务的jar包及Demo"应该包含了一个运行示例,帮助我们理解如何在Spring应用中设置和运行定时任务。下面,我们将深入探讨Spring Task的核心概念和关键配置。 首先,Spring Task提供了两种主要的方式...
总之,"springboot-scheduler定时任务学习demo源码"是一个很好的学习资源,它涵盖了Spring Boot定时任务的基本用法和配置,包括`@Scheduled`、`@EnableScheduling`、cron表达式以及异步任务执行。通过阅读和分析这个...
总结,`schedule_demo.zip`的案例主要涉及了Spring定时任务的配置和使用,可能是通过`@Scheduled`注解来实现简单的定时任务,也可能是通过Quartz库进行更复杂的调度。通过这个示例,我们可以学习到如何在Java应用中...
- 在Spring Boot应用中,`@SpringBootApplication`启动类上添加`@ComponentScan`注解,确保扫描到包含`@Scheduled`的方法。 - 可以通过`ApplicationContext`获取`Scheduler`实例,手动暂停、恢复或关闭调度器。 5...
《深入理解Spring Task:基于项目spring-task-demo的实践解析》 Spring Task,是Spring框架中的一个强大组件,它为开发者提供了在应用内部执行定时任务的能力。在这个名为"spring-task-demo"的项目中,我们将深入...
Spring提供了一个名为`@Scheduled`的注解,可以方便地将方法标记为定时任务。 1. **使用@Scheduled** - 首先,我们需要配置一个`TaskScheduler`或`ScheduledExecutorService`,并在Spring配置文件中声明。 - 然后...
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class SchedulingComponent { / * 测试定时任务,没三秒执行一次 */ @...
Spring Boot提供了简单易用的API和注解来支持异步任务的实现,特别是通过`@Async`注解和定时任务`@Scheduled`。下面我们将深入探讨这两个核心概念。 ### `@Async` 注解 `@Async`是Spring提供的一个注解,用于标记...