java实现定时任务 schedule_spring schedule定时任务(一):注解的方式-阿里云开发者社区...

本文介绍了如何在Java中使用Spring Schedule通过注解的方式来实现定时任务。首先,需要引入相关依赖并配置spring.xml文件。然后,通过在业务类上添加@Component注解,并在需要执行的定时任务方法上使用@Scheduled(cron = "0/5 * * * * ?")注解来定义任务的执行周期。最后,可以通过ContextLoaderListener或DispatcherServlet在web.xml中配置以启动定时任务。
摘要由CSDN通过智能技术生成

我所知道的java定时任务的几种常用方式:

1、spring schedule注解的方式;

2、spring schedule配置文件的方式;

3、java类继承TimerTask;

第一种方式的实现:

1、使用maven创建spring项目,schedule在spring-context.jar的包下边,因此需要导入与之相关的包;同时,我配的是spring

web项目,也同时导入了spring-web和spring-webmvc的包,如下:

org.springframework

spring-context

4.1.7.RELEASE

org.springframework

spring-web

4.1.6.RELEASE

org.springframework

spring-webmvc

4.1.6.RELEASE

maven导包配置只需要如下就好,其他相关的依赖,maven会自行解决。

2、配置spring项目的基础文件spring.xml:

xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task-3.1.xsd">

3、编写java业务代码,需要在类声明上边添加@Component注解,并在需要定时任务执行的方法声明上添加@Scheduled(cron = "0/5 * * * * ?")注解以及相关的参数。

package scheduleTest;

import java.text.SimpleDateFormat;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

/**

* spring定时器1

*

* @author tuzongxun123

*

*/

@Component

public class ScheduleTest {

@Scheduled(cron = "0/5 * * * * ?")

public void schTest1() {

Date date = new Date();

SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dateStr = sim.format(date);

System.out.println("这是spring定时器1,每五秒执行一次,当前时间:" + dateStr);

}

}

4、web项目的基础配置文件web.xml,:

appversion

contextConfigLocation

classpath:spring.xml

spring监听器

org.springframework.web.context.ContextLoaderListener

index.jsp

上边的配置中使用了spring的上下文监听器,在这种情况下项目启动后,spring.xml中的定时任务配置才会生效。但是这不是唯一的方法,也可以使用如下的配置,启动项目后可以看到一样的效果:

appversion

contextConfigLocation

classpath:spring.xml

dispatcher

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:spring.xml

1

dispatcher

/

index.jsp

这里是吧spring的监听器换成了mvc的调度器,在调度器加载的时候就运行spring.xml中的定时任务配置,因此启动项目后看到效果一样。如果把上边的监听器和mvc的调度器一起配在这里,会看到启动项目后同一时间内这个定时任务需要执行的业务会执行两次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值