`
jbgtwang
  • 浏览: 21790 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

Scheduled Jobs in Spring 3

 
阅读更多

Scheduled Jobs in Spring 3

Matt Young // in Technology

Spring has made scheduling a Java method as easy as creating a UNIX cron job. Here's a quick introduction.

Those of us who got our start writing web applications in the early days were used to having cron available to us to run PERL scripts when we needed a periodic task executed. Over time, the evolution of web applications into the application server space has made it a little less convenient to run your business logic at an appropriate interval. 

Within the Java world, Quartz is a commonly used technology introduced to solve the problem.

But the people behind Spring have, as with most things, boiled the process down to something very simple.

Spring 2 had a useful task executor and task scheduler, but Spring 3 has evolved the process into easy annotation-based awesomeness. Java methods that you've already written to generate reports, do maintenance, or check status can all be run with common cron interval definitions.

Here's a quick set of steps you can use to set up this kind of scheduled task within your Spring-based Java application:

Step 1: Define a task executor and task scheduler in an application context file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd ">
<task:scheduler id="taskScheduler"/>
<task:executor id="taskExecutor" pool-size="1"/>
<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler"/>
</beans>

The "task" namespace is used here to declare the scheduler and executor. The third line of the XML asks Spring to scan classes for annotations related to scheduled tasks. If you have multiple tasks to run at the same time, you can get them to run in parallel by increasing the pool size.

Step 2: Annotate the method you want to run on a schedule

@Service
public class ReportingServiceImpl implements ReportingService {
private static final Logger logger = Logger.getLogger(ReportingServiceImpl.class);

@Autowired
private MailService ms;
@Override
// Every night at 1 AM
@Scheduled(cron = "* * 1 * * ?")
public void generateAndEmailReport() {
logger.info("Starting report at " + new Date(System.currentTimeMillis()));
Report r = generateReport();
ms.sendReport(r);
logger.info("Report sent at " + new Date(System.currentTimeMillis()));
}
}

 

Simple!

There are some other useful variants of the annotations. Instead of supplying a 'cron' pattern, you could just define an interval.

@Scheduled(fixedRate=60000)

This annotation would have a method run every 60 seconds. (FixedRate defines a time in milliseconds)

You can also use the

@Async

annotation to mark a scheduled method as asynchronous.

Two things to be aware of:

At the time of writing, there's no way to control if or how often a method is retried if an exception occurs during scheduled method execution. So, if an exception happens during execution of a scheduled method, Spring will re-try the method automatically. If the exception continues to happen, this can result in large logs and possibly a lot of resource consumption. I've submitted an enhancement request to Spring to make this behavior configurable. http://jira.springframework.org/browse/SPR-6860

Spring 3.0.0 Release had a bug where web apps with a task scheduler would end up executing scheduled methods twice. This has been resolved in Spring 3.0.1.

You can read more about scheduling tasks with Spring here: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

 

转自:http://www.vodori.com/blog/spring3scheduler.html

其他参考:http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/scheduling.html

分享到:
评论

相关推荐

    laravel-scheduled-jobs-on-heroku:Heroku上的Laravel Scheduled Jobs的代码示例

    3. 在`Kernel.php`中定义Scheduled Jobs。 4. 创建`Procfile`以启动`clock`进程。 5. 更新`composer.json`以在部署时执行数据库迁移。 6. 使用`git push heroku main`部署应用并启动`clock`进程。 通过以上步骤,你...

    spring3整合quartz1.8和spring3整合quartz2.2两个版本示例

    3. **配置方式**:Quartz 2.x 引入了新的配置方式,如使用 XML 或注解来配置 Jobs 和 Triggers。Spring 也支持使用 `@Component` 注解来定义 Job 类,以及 `@Configuration` 和 `@EnableScheduling` 来开启任务调度...

    spring_quartz项目可以直接运行

    3. **声明式触发**:通过 Spring 的 @Scheduled 注解,可以实现声明式任务调度,使得任务调度变得更加直观和简单。 **三、Spring Quartz 的基本概念** 1. **Job**:代表一个具体的任务,包含任务执行的逻辑。 2. *...

    spring时间调度配置

    在实际开发中,Spring的时间调度主要通过两种方式实现:`Scheduled`注解和Quartz集成。 ### 二、基于`Scheduled`注解的任务调度 `Scheduled`注解是Spring中最简单的定时任务实现方式之一。只需要在目标方法上添加...

    spring 集成quartz 用数据库实现quartz的集群

    在Spring中,我们可以通过`@EnableScheduling`注解开启定时任务支持,然后通过`@Scheduled`注解在方法上定义定时规则。但这仅限于单机环境,若要实现分布式定时任务,我们需要引入Quartz。 集成Quartz的第一步是...

    quartz 在spring中使用服务定时执行的例子

    在Spring中,我们还可以利用`@Scheduled`注解在方法上直接声明定时任务,但这种方式无法享受到Quartz的高级特性,如并发控制、集群支持等。 最后,为了使定时任务在Spring Boot启动时自动运行,我们需要在主应用类...

    Java Oracle JOBS 自动调度

    此外,Spring框架中的`org.springframework.scheduling`模块也提供了丰富的定时任务管理,如`@Scheduled`注解,方便在Spring应用中集成定时任务。 接下来,Oracle数据库提供了DBMS_SCHEDULER包来创建和管理数据库...

    springboot中通过注解使用quartz

    import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @DisallowConcurrentExecution public class MyJob { @Scheduled(cron = "0 0/5 * ...

    面试准备1

    - **Quartz**:Quartz是一个开源的作业调度框架,它可以与Spring框架集成,通过创建配置文件如`spring-quartz.xml`来定义Jobs和Triggers,实现更复杂的定时任务调度。 2. **技术栈** - **Spring Boot**:是一个...

    Springboot2+quartz实现定时器的增删改查.rar

    在Spring Boot中,我们可以通过实现`org.springframework.scheduling.Trigger`和`org.springframework.scheduling.Task`接口来自定义定时任务,或者使用`@Scheduled`注解来声明定时任务。这里我们使用`@Scheduled`为...

    sping+ springMVC+mybatis分页,定时任务

    至于定时任务,Spring框架提供了Spring Task(也称为Spring Jobs)来处理定时任务。开发者可以使用@Scheduled注解来标记一个方法,使其按照指定的时间间隔执行。例如,可以设置每天凌晨执行某个清理过期数据的函数。...

    job-redislogin-demo.rar(动态定时任务)

    SpringBoot提供了两种方式来处理定时任务:Spring的`@Scheduled`注解和Quartz Scheduler。在“job-redislogin-demo”中,可能使用的是`@Scheduled`注解,因为这种方式更加简单且易于集成。 1. **Spring定时任务**:...

    quartz_api_1.65的API

    在Spring框架中,可以通过Spring的TaskScheduler接口和@Scheduled注解来实现定时任务,但也可以与Quartz API结合使用,提供更高级别的调度功能。Spring的QuartzJobBean简化了在Spring容器中使用Quartz Job的配置。 ...

    springboot整合Quartz.zip

    现在,你可以通过`@Scheduled`注解在SpringBoot应用中创建基于cron表达式的简单定时任务,或者使用Quartz的复杂调度功能。通过这种方式,SpringBoot和Quartz的整合使你能够在Java应用程序中实现灵活且可扩展的定时...

    Quartz-demo

    3. **Scheduler**: 调度器是Quartz的核心,负责管理和执行Jobs和Triggers。你可以通过`Scheduler`实例来安排Job的执行。 4. **JobDetail**: 描述Job的具体信息,包括Job类、数据绑定等。它是Job的一个实例化,包含...

    Quartz Scheduler入门

    Spring的`@Scheduled`注解提供了更简洁的定时任务声明方式,而Quartz则提供了更强大的定制能力。 总结,Quartz Scheduler是一个功能强大且灵活的任务调度框架,适用于各种定时任务需求。通过理解其核心组件和使用...

    Scheduler_APITests

    使用@EnableScheduling注解可以开启后台任务调度,然后通过@Scheduled注解定义定时任务。 测试Scheduler_APIs的关键在于确保任务能够准确地启动、执行和停止,同时要考虑并发性和资源管理。以下是一些测试策略: -...

    jobrunr:在Java中执行后台处理的极其简单的方法。 由持久性存储支持。 开放供商业使用

    println( " This is all you need for distributed jobs! " )); 仅使用Java 8 lambda即可在Java应用程序内执行即发即忘,延迟,计划和重复执行的工作的极其简便的方法。 支持CPU和I / O密集型,长时间运行和短期...

    定时登陆模块

    在编程中,常见的定时任务框架有Java的Quartz、Spring的Scheduled Tasks以及Linux下的Cron Jobs等。这些工具能够帮助我们设定定时任务的执行计划,并在指定时间触发特定的函数或方法,例如登录操作。 对于定时登录...

Global site tag (gtag.js) - Google Analytics