Spring 在web应用中的定时器

本文介绍如何在Java中使用Spring框架实现定时任务的执行,包括创建自定义类、配置web.xml文件、Spring配置文件及启动时自动执行任务的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.先创建要执行任务的java类

package com.witon.test;


import java.text.SimpleDateFormat;
import java.util.Date;


public class Test {


public String getParam() {
 return param;
}
public void setParam(String param) {
 this.param = param;
}
private String param;
 
public void run(){
 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 System.out.println("the param is:"+param+" ! Time is "+ format.format(new Date()));
}
}

2.web.xml配置


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <listener>
  <listener-class>
  org.springframework.web.context.ContextLoaderListener
  </listener-class>
  </listener>
</web-app>


3.spring配置

<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 定义我们要运行的类,可以使用注入,定制一些参数 -->
<bean id="businessTestTime" class="com.witon.test.Test">
<property name="param" value="Spring Timer test"></property>
</bean>
 <!-- 每个定义的任务都要在这里引用才能运行 schedule:时刻表、清单、目录 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref local="businessTestTrigger" />
</list>
</property>
</bean>
 <!-- 引用、配置要运行的方法 -->
<bean id="businessTestDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="businessTestTime" />
</property>
<!-- 是否同时发生 -->
<property name="concurrent" value="false"></property>
<!-- 目标方法 -->
<property name="targetMethod" value="run"></property>
</bean>

<!-- 引用、定制时间间隔 -->
 <bean id="businessTestTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
  <property name="jobDetail">
   <ref bean="businessTestDetail"/>
  </property>
  <property name="cronExpression">
   <value>0/5 * * * * ?</value>
  </property>
 </bean>
</beans>

4.启动时自动执行任务列表



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值