前言

译文链接:http://websystique.com/spring/spring-job-scheduling-with-scheduled-enablescheduling-annotations/

本文展示如何使用Spring的@Scheduled和@EnableScheduling注解来实现任务调度功能。

涉及技术及开发工具

  • Spring 4.0.6.RELEASE
  • Maven 3
  • JDK 1.6
  • Eclipse JUNO Service Release 2

工程目录结构

步骤一:往pom.xml中添加依赖

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.websystique.spring</groupId>
<artifactId>SpringSchedulingAnnotationExample</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>SpringSchedulingAnnotationExample</name> <properties>
<springframework.version>4.0.6.RELEASE</springframework.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build> </project>

步骤二:创建Spring配置类

Spring配置类是指用@Configuration注解标注的类,这些类包含了用@Bean标注的方法。这些被@Bean标注的方法可以生成bean并交由spring容器管理。

package com.websystique.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling; import com.websystique.spring.scheduling.MyBean; @Configuration
@EnableScheduling
public class AppConfig { @Bean
public MyBean bean() {
return new MyBean();
} }

这里要注意下@EnableScheduling注解,该注解开启了Spring的定时任务能力,使用该注解后,所有被@Scheduler标注的bean方法将会被注册用于调度。

如下是bean类:

package com.websystique.spring.scheduling;

import org.springframework.scheduling.annotation.Scheduled;

public class MyBean {

    @Scheduled(fixedRate=5000)
public void printMessage() {
System.out.println("I am called by Spring scheduler");
}
}

以上被@Scheduled标注的方法会每隔五秒调用一次;

注意被@Scheduled标注的方法返回值是void且不能有参数,当然你可以注入其它bean,然后在printMessage方法内部实现其它额外功能。

@Scheduled注解提供若干种属性配置用于指定不同的调度时间:

initialDelay:在方法第一次执行之前等待的毫秒数;

fixedRate:方法每次开始执行的毫秒间隔,与该方法什么时候执行结束无关;

fixedDelay:上一次方法执行结束到下一次方法开始执行的毫秒间隔;

cron:提供更加详细的控制,如@Scheduled(cron=*/5 * * * * MON-FRI")表示在工作日每隔五秒执行一次

步骤三:创建main方法执行

package com.websystique.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext; import com.websystique.spring.config.AppConfig; public class AppMain { @SuppressWarnings({ "unused", "resource" })
public static void main(String args[]){
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
} }

注意这里我们并没有显式的调用任何调度类或方法,仅仅简单的注册了我们的配置类;

但是,由于我们使用了@EnableScheduling注解,被@Scheduler标注的bean方法会自动注册为计划任务去执行。

运行以上程序,结果如下:

I am called by Spring scheduler
I am called by Spring scheduler
I am called by Spring scheduler
I am called by Spring scheduler
I am called by Spring scheduler
.....

最后,假如你的任务需要花费很长的时间去完成,而且频率很高,你可以使用指定大小的线程池去处理各个方法中的任务,如下所示:

package com.websystique.spring.config;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar; import com.websystique.spring.scheduling.MyBean; @Configuration
@EnableScheduling
public class AppConfig implements SchedulingConfigurer { @Bean
public MyBean bean() {
return new MyBean();
} @Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
} @Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(10);
} }

以上配置使用的线程池大小为10,运行以上程序,可以得到相同的结果。

工程源码

http://websystique.com/?smd_process_download=1&download_id=811

【译】Spring 4 基于TaskScheduler实现定时任务(注解)的更多相关文章

  1. Spring 中基于 AOP 的 @AspectJ注解实例

    @AspectJ 作为通过 Java 5 注释注释的普通的 Java 类,它指的是声明 aspects 的一种风格.通过在你的基于架构的 XML 配置文件中包含以下元素,@AspectJ 支持是可用的 ...

  2. Spring 3.1新特性之二:@Enable*注解的源码,spring源码分析之定时任务Scheduled注解

    分析SpringBoot的自动化配置原理的时候,可以观察下这些@Enable*注解的源码,可以发现所有的注解都有一个@Import注解.@Import注解是用来导入配置类的,这也就是说这些自动开启的实 ...

  3. spring boot集成swagger,自定义注解,拦截器,xss过滤,异步调用,guava限流,定时任务案例, 发邮件

    本文介绍spring boot集成swagger,自定义注解,拦截器,xss过滤,异步调用,定时任务案例 集成swagger--对于做前后端分离的项目,后端只需要提供接口访问,swagger提供了接口 ...

  4. Spring @Bean注解 (基于java的容器注解)

    基于java的容器注解,意思就是使用Java代码以及一些注解,就可以取代spring 的 xml配置文件. 1-@Configuration & @Bean的配合 @Configuration ...

  5. Spring:基于注解的Spring MVC

    什么是Spring MVC Spring MVC框架是一个MVC框架,通过实现Model-View-Controller模式来很好地将数据.业务与展现进行分离.从这样一个角度来说,Spring MVC ...

  6. 【Spring】Spring的定时任务注解@Scheduled原来如此简单

    1 简介 定时任务的实现非常多,JDK的Timer.Spring提供的轻量级的Scheduled Task.QuartZ和Linux Cron等,还有一些分布式的任务调度框架.本文主要介绍Schedu ...

  7. Spring基于SchedulingConfigurer实现定时任务

    Spring 基于 SchedulingConfigurer 实现定时任务,代码如下: import org.springframework.scheduling.annotation.Schedul ...

  8. Spring boot 基于注解方式配置datasource

    Spring boot 基于注解方式配置datasource 编辑 ​ Xml配置 我们先来回顾下,使用xml配置数据源. 步骤: 先加载数据库相关配置文件; 配置数据源; 配置sqlSessionF ...

  9. Spring boot 基于Spring MVC的Web应用和REST服务开发

    Spring Boot利用JavaConfig配置模式以及"约定优于配置"理念,极大简化了基于Spring MVC的Web应用和REST服务开发. Servlet: package ...

随机推荐

  1. APUE中fcntl.h的使用及O_SYNC在Mac与Ubuntu下的测试

    此部分测试涉及到APUE V3中,第三章的图3-12到图3-14. 通过fcntl.h提供的功能,修改fd的文件属性,本处增加O_SYNC功能,并测试其效果. 本文涉及代码: tree ch3 ch3 ...

  2. hibernate一对一主键双向关联

    关联是类(类的实例)之间的关系,表示有意义和值得关注的连接. 本系列将介绍Hibernate中主要的几种关联映射 Hibernate一对一主键单向关联Hibernate一对一主键双向关联Hiberna ...

  3. JavaScript中的apply,call与this的纠缠

    1.apply定义 apply:调用函数,并用指定对象替换函数的 this 值,同时用指定数组替换函数的参数. 语法:apply([thisObj[,argArray]]) thisObj 可选.要用 ...

  4. ElasticSearch 5学习(6)——分布式集群学习分享1

    在使用中我们把文档存入ElasticSearch,但是如果能够了解ElasticSearch内部是如何存储的,将会对我们学习ElasticSearch有很清晰的认识.本文中的所使用的ElasticSe ...

  5. LOCK TABLES和UNLOCK TABLES与Transactions的交互

    LOCK TABLES对事务不安全,并且在试图锁定表之前隐式提交任何活动事务. UNLOCK TABLES只有在LOCK TABLES已经获取到表锁时,会隐式提交任何活动事务.对于下面的一组语句,UN ...

  6. 制作自己的MVC框架(一)——简单粗暴的实现

    现在市面上有很多成熟的MVC框架,可以拿来直接用,但自己造一下轮子其实也挺有意思的. 下面先来看个最简单粗暴的MVC实现. 5个文件就能实现最简单的MVC,在Apache中设置一个虚拟目录,配置个简单 ...

  7. 使用TypeScript拓展你自己的VS Code!

    0x00 前言 在前几天的美国纽约,微软举行了Connect(); //2015大会.通过这次大会,我们可以很高兴的看到微软的确变得更加开放也更加务实了.当然,会上放出了不少新产品和新功能,其中就包括 ...

  8. JQuery Datatables Columns API 参数详细说明

    ---恢复内容开始--- Data Tables: http://datatables.NET/ Version: 1.10.0 Columns说明 虽然我们可以通过DOM直接获取DataTables ...

  9. 【WPF】ChartControl的使用

    一.前言       本月正好做一些关于工程4D,5D的界面展示,正好要用到Dev控件中的ChartControl控件,也就是图表控件. 折腾了两星期完成了一个比较能说的过去的界面吧.(领导要求高,可 ...

  10. Chart: Who pays the most in Seattle for software engineers

    http://www.geekwire.com/2012/chart-pays-seattle-software-engineers/ Chart: Who pays the most in Seat ...