spring 实现定时任务(手动配置,不用注解)

发布时间 2023-09-08 17:09:56作者: Marydon

1.情景展示

在java当中实现定时任务,主要有两种。

一种是通过java源码实现,另一种是通过spring框架来实现。

由于我们现在基本上使用的都是spring框架(SpringMVC、SpringBoot),况且,使用spring实现定时任务,代码更加简洁。

那么,如何是想spring来实现呢?

2.具体分析

使用spring实现,具体有两种。

一种是在spring框架中,手动配置定时任务;

另一种是使用注解。(SpringMVC和SpringBoot均可)

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: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"
	>
	
	<description>
        <![CDATA[
		    描述:远程医疗定时任务配置
		    版本:1.0
		    作者:Marydon
		    日期:2023年9月4日10:59:00
		    说明:定时任务需要注入的对象,可以在这个文件当中配置,也是配置到spring-ycyl-bo.xml当中
	    ]]>
	</description>
	
	<!-- 外检:定时任务类 -->
	<bean id="wjJobTasksBean" class="ycyl.web.jobs.WjJobTasks">
    	    <property name="boWJ_CONSULT_INFO" ref="boWJ_CONSULT_INFO" />
    	    <property name="boWJ_PATIENT_INFO" ref="boWJ_PATIENT_INFO" />
    	    <property name="boWJ_PATIENT_DETAILINFO_RESULT" ref="boWJ_PATIENT_DETAILINFO_RESULT" />
        </bean>
    
	<!-- 
		通过task标签,定义定时功能
		在线Cron表达式生成器:https://cron.qqe2.com/
	 -->
	<task:scheduled-tasks>
		<!-- 
			wjJobTasksBean对象的getReport方法
			每10分钟执行一次:0 0/10 * * * ?
		-->
		<task:scheduled ref="wjJobTasksBean" method="getReport" cron="0 0/10 * * * ?"/>
		<!-- 要关闭定时任务,需将task:scheduled-tasks标签删掉 -->
	</task:scheduled-tasks>

</beans>

说明:

为了方便对定时任务管理,我们可以把定时任务单独拉出来,搞成一个独立的XML文件。

xmlns="http://www.springframework.org/schema/beans"对应的值是:http://www.springframework.org/schema/beans和http://www.springframework.org/schema/beans/spring-beans.xsd

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"对应的是:xsi:schemaLocation

xmlns:task="http://www.springframework.org/schema/task"对应的值是: http://www.springframework.org/schema/task和http://www.springframework.org/schema/task/spring-task-3.0.xsd

以上信息,不能省略,必须引用到beans标签里面,否则,启动会报错。

然后,我们再把这个文件引入到spring核心文件当中即可。 

WjJobTasks.java类的getReport()方法就是我需要定时执行的内容。

另外,就是通过手动配置的这种方式,会在项目启动的时候自动生效,不需要我们进行额外的操作。

写在最后

  哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!

 相关推荐: