> 版本说明

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.14.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.3.4.RELEASE</version>
</dependency> <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>

> 搭建最简单的Spring定时任务工程

Spring定时任务,给人的第一感觉就是简洁(>_<)

所需要的JAR,参考以上“版本说明”的POM文件,当然,不嫌麻烦,也可以一个个去下载。

把Spring通过web.xml注册进来

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/spring.xml</param-value>
</context-param> <listener>
<description>Spring Context</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

当然,需要告诉Spring去哪儿扫描组件。对了,也要告诉Spring我们是使用注解方式注册任务的

<?xml version="1.0" encoding="UTF-8"?>
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"> <context:component-scan base-package="com.nicchagil.*"/>
<task:annotation-driven/> </beans>

附logback的配置

<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder
by default -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender> <appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>D:/logs/application.log</file>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender> <root level="debug">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
</configuration>

好了,注册一个简单的任务,它每逢0秒执行,打印一个语句

package com.nicchagil.springtask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; @Component
public class MyFirstSpringJob {
    
private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Scheduled(cron = "0 * * * * ?")
    public void run() {
        logger.info("MyFirstSpringJob trigger...");
    } }

如无意外,启动项目后,可见日志大致如下

22:42:00.024 [pool-1-thread-1] INFO  c.n.springtask.MyFirstSpringJob - MyFirstSpringJob trigger...
22:43:00.002 [pool-1-thread-1] INFO  c.n.springtask.MyFirstSpringJob - MyFirstSpringJob trigger...

> 如果你同时执行多个任务,且某些任务耗时较长,要配线程池

如题。比如,你设置了12:00触发A任务、12:05触发B任务,如果A任务需耗时10分钟,并且没设置线程池,那么B任务有可能会被推迟到12:10以后再执行哦。

所以,这些情况,我们需设置线程池

<task:annotation-driven scheduler="myScheduler"/>
<task:scheduler id="myScheduler" pool-size="20"/>

:具体池的大小,视项目情况而定

将任务改为如下测试

第一个任务

package com.nicchagil.springtask;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; @Component
public class MyFirstSpringJob { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Scheduled(cron = "0 * * * * ?")
public void run() {
logger.info("MyFirstSpringJob trigger..."); /* 模拟此Job需耗时5秒 */
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }

第二个任务

package com.nicchagil.springtask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; @Component
public class MySecondSpringJob { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Scheduled(cron = "3 * * * * ?")
public void run() {
logger.info("MySecondSpringJob trigger...");
} }

由日志可以看出,第一个任务由一个线程执行;而第二个任务启动时,由于第一个任务还未完成,则由另外一个线程执行

22:49:00.023 [myScheduler-1] INFO  c.n.springtask.MyFirstSpringJob - MyFirstSpringJob trigger...
22:49:03.002 [myScheduler-2] INFO c.n.springtask.MySecondSpringJob - MySecondSpringJob trigger...

Java_spring_定时执行任务的更多相关文章

  1. C#定时执行

    代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; ...

  2. MVC 定时执行任务

    环境:.net4.5 需求:需要一个方法定时执行任务 解决: System.Threading.Timer 提供以指定的时间间隔执行方法的机制. 此类不能被继承,有10多种实例化方法,满足多种情况. ...

  3. 【转】linux 定时执行shell脚本

    在oracle 中可以利用dbms_job包定时执行pl/sql.sql过程,在像备份等需要在操作系统级定时任务只能采用crontab来完成 本文讲述crontab具体用法,以供备忘. 在oracle ...

  4. Linux下定时执行脚本(转自Decode360)

    文章来自:http://www.blogjava.net/decode360/archive/2009/09/18/287743.html Decode360's Blog  老师(业精于勤而荒于嬉 ...

  5. [转]oracle job有定时执行的功能,可以在指定的时间点或每天的某个时间点自行执行任务。

    oracle job有定时执行的功能,可以在指定的时间点或每天的某个时间点自行执行任务. 一.查询系统中的job,可以查询视图 --相关视图 select * from dba_jobs; selec ...

  6. linux定时执行任务crontab命令用法

    linux系统的定时任务是由 cron (crond) 这个系统服务来控制的.Linux 系统上面原本就有非常多的计划性工作,因此这个系统服务是默认启动的.另外, 由于使用者自己也可以设置计划任务,所 ...

  7. ORACLE 定时执行存储过程

    推荐用dbms_scheduler方式更好 (2012-11-19注) /* 查询: select job,broken,what,interval,t.* from user_jobs t; job ...

  8. oracle job有定时执行的功能,可以在指定的时间点或每天的某个时间点自行执行任务。

    来源于:http://www.cnblogs.com/wangfg/p/5110831.html 一.查询系统中的job,可以查询视图 --相关视图 select * from dba_jobs; s ...

  9. linux下定时执行任务方法【转】

     之前就转过一篇关于定时任务的文章,前俩天用,还的翻出来看!!!再转一次,备用,,需要的时候不用麻烦找! ----------------------------------------------- ...

随机推荐

  1. [Web API] 如何让 Web API 统一回传格式以及例外处理[转]

    [Web API] 如何让 Web API 统一回传格式以及例外处理 前言 当我们在开发 Web API 时,一般的情况下每个 API 回传的数据型态或格式都不尽相同,如果你的项目从头到尾都是由你一个 ...

  2. cocos2d-x知识巩固-基础篇(2)

    上一篇博客介绍了整个cocos2dx引擎需要掌握的各个模块,每一个模块实际上往深了研究都有难点,后面我会详细地去分析它的用法.今天我们从第一个模块说起,即渲染模块.首先,为了理解,我们做个类比,说明该 ...

  3. How to interact with the Chef Server using the Chef Server API using Shell script

    !/usr/bin/env bash   _chef_dir () { # Helper function: # Recursive function that searches for chef c ...

  4. 第二百九十四天 how can I 坚持

    这是怎么了,好难受,晚上都没吃饭,全身都疼.该咋办. 其实,真的是身体最重要. 洗洗睡了.好难受.

  5. Java设计模式系列之桥接模式

    桥接模式(Bridge)的定义 在软件系统中,某些类型由于自身的逻辑,它具有两个或多个维度的变化,那么如何应对这种“多维度的变化”?这就要使用桥接模式 将抽象部分与它的实现部分分离,使它们都可以独立地 ...

  6. iOS WebServiceFramework网络服务框架浅解

    网络服务几乎是每一款成功APP的必备条件,打开你手机你会发现里面不用联网的应用数量十只手指可以数出来,就算是一些以独特技术切入市场的APP如美颜相机,都至少加入了分享功能.下面我先做下简单的回顾兼扫盲 ...

  7. zoj 1610 Count the Colors

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=610  Count the Colors Time Limit:2000MS   ...

  8. C#中垃圾回收与内存管理机制

    今天抽空来讨论一下.Net的垃圾回收与内存管理机制,也算是完成上个<WCF分布式开发必备知识>系列后的一次休息吧.以前被别人面试的时候问过我GC工作原理的问题,我现在面试新人的时候偶尔也会 ...

  9. C语言经典算法100例(一)

    C语言中有有许多经典的算法,这些算法都是许多人的智慧结晶,也是编程中常用的算法,这里面包含了众多算法思想,掌握这些算法,对于学习更高级的.更难的算法都会有很大的帮助,会为自己的算法学习打下坚实的基础. ...

  10. java选项及系统属性

    java选项 -d32 使用 32 位数据模型 (如果可用) -d64 使用 64 位数据模型 (如果可用) -server 选择 "server" VM 默认 VM 是 serv ...