spring定时器如何使用?
步骤1. 定义job bean
1.TaskScheduler构造
2.初始化相关服务
<bean id="xxxxScheduler" class="com.xxxx.TaskScheduler">
<property name="xxxxService" ref="xxxxService"/>
<property name="xxxxService" ref="xxxxService"/>
<property name="xxxxService" ref="xxxxService"/>
<property name="xxxxService" ref="xxxxService"/>
<property name="xxxxService" ref="xxxxService"/>
<property name="xxxxService" ref="xxxxService"/>
</bean>
步骤2. 定义一个joblist bean来统一管理job
<bean id="listScheduler" class="com.xxxx.ListScheduler">
<property name="schedulerList">
<list>
<ref bean="xxxxScheduler" />
<ref bean="xxxxScheduler"/>
<ref bean="xxxxScheduler" />
<ref bean="xxxxScheduler"/>
</list>
</property>
<property name="FinishHour" value="xxx"/>
<property name="ExecHour" value="xxx"/>
</bean>
步骤3.定义job factorybean和CronTriggerBean
<!--注册定时器信息-->
<bean id="SchedulerTriggerJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="listScheduler" />//定时任务列表
<property name="targetMethod" value="start" />//启动方法
<property name="concurrent" value="false" />//指定最终封装出的任务是否有状态
</bean>
<!--说明:Spring中使用Quartz的2种方法(extends QuartzJobBean与使用MethodInvokingJobDetailFactoryBean)-->
<bean id="SchedulerTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<!--配置定时器任务的调度器-->
<property name="jobDetail" ref="SchedulerTriggerJobDetail" />
<property name="cronExpression">
<value>0 0 0 * * ?</value>
</property>
</bean>
<!--说 明:org.springframework.scheduling.quartz.CronTriggerBean是spring提供的触发器,在这个 触发器中设定了要触发的job,同时设定了触发时间(cronExpression)-->
4 <!--注册监听器-->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="schedulerName" value="xxxx"/>
<property name="quartzProperties">
<props>
<prop key="org.quartz.threadPool.threadCount">2</prop>
</props>
</property>
<property name="triggers">
<list>
<ref bean="schedulerTrigger" />
</list>
</property>
</bean>
<!--说明:org.springframework.scheduling.quartz.SchedulerFactoryBean这是一个spring的工厂bean,监听器:当spring关闭前,自动关闭scheduler,在triggers属性列表中加入定义的触发器,这里可以定义多个触发器-->
spring定时器实现原理?
核心概念
微信公众号: 架构师日常笔记 欢迎关注!