前言

译文链接: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. Android-Eclipse-INSTALL_FAILED_UPDATE_INCOMPATIBLE错误

    电脑重装了系统,环境问题一大堆,唉,搞死人,这不,今天就出现了这样的一个奇怪的问题. INSTALL_FAILED_UPDATE_INCOMPATIBLE 最后搜了一遍,发现是因为已经安装了这个包,包 ...

  2. BVT & BAT (版本验证测试和版本验收测试)

    BVT & BAT 版权声明:本文为博主原创文章,未经博主允许不得转载. 一.BVT: (Build Verification Test ) BVT的概念: BVT(版本验证测试)是在所有开发 ...

  3. JS原生第三篇 (帅哥)

    1.1 数 组 1. 数组           看电影    电影院  座位 大的变量     里面可以放很多的值 var  arr = [1,3,57]; var ar = new Array(); ...

  4. 大数据时代下的SQL Server第三方负载均衡方案----Moebius测试

    一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 架构原理(Architecture) 测试环境(Environment) 安装Moebius( ...

  5. 【.NET深呼吸】Zip文件操作(1):创建和读取zip文档

    .net的IO操作支持对zip文件的创建.读写和更新.使用起来也比较简单,.net的一向作风,东西都准备好了,至于如何使用,请看着办. 要对zip文件进行操作,主要用到以下三个类: 1.ZipFile ...

  6. scheduleInRunLoop作用

    例子一: - (void)setUpStreamForFile:(NSString *)path { // iStream is NSInputStream instance variable iSt ...

  7. SQL Server-聚焦EXISTS AND IN性能分析(十六)

    前言 前面我们学习了NOT EXISTS和NOT IN的比较,当然少不了EXISTS和IN的比较,所以本节我们来学习EXISTS和IN的比较,简短的内容,深入的理解,Always to review ...

  8. SQLServer:什么是主键(PK)和外键(FK)?

    一.主键与外键 1.主键是用来唯一地标识一行数据.主键列必须包含唯一的值,且不能包含空值(null). 2.主键可以建立在每张二维表中单列或者多列上. 3.一张二维表上的外键可以引用另一张二维表上对应 ...

  9. IOS 封装功能和逻辑思想

    在ios开发中,难免会用到helper的思想.这篇就简单讲解下关于helper的简单实用方法. 假设我们要做一个这样的界面: 会议分为四种情况: 未召开 正在召开 已结束 已取消 再看看逻辑关系: 编 ...

  10. 微信小程序基础入门

    准备 Demo 项目地址 https://github.com/zce/weapp-demo Clone or Download(需准备GIT环境) $ cd path/to/project/root ...