sping+quartz定时任务的最简单实践

Posted seeall

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sping+quartz定时任务的最简单实践相关的知识,希望对你有一定的参考价值。

1,启动spring容器

  Tomcat启动的时候,加载web.xml的listener和context-param,spring的listener监听到对应的contextConfigLocation创建事件后,开始启动spring容器;

  <listener>
  <description>spring监听器</description>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <context-param>
   <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring.xml</param-value>
  </context-param>

 

2,初始化定时任务相关的bean

    技术图片                                  技术图片

 

3,初始化 org.springframework.scheduling.quartz.SchedulerFactoryBean

  参考    https://blog.csdn.net/beliefer/article/details/51578546 ;

  <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="triggers">
  <list>
  <ref bean="hitBeibeiTrigger" />
  <ref bean="hitBeibeiTrigger2" />
  </list>
  </property>
  <property name="configLocation" value="classpath:quartz.properties"/>
  </bean>

 

4,初始化 org.springframework.scheduling.quartz.CronTriggerFactoryBean

  <bean id="hitBeibeiTrigger"
  class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
  <property name="jobDetail" ref="hitBeibeiJob"/>
  <property name="cronExpression" value="0/30 * * * * ?"/>
  </bean>

  <bean id="hitBeibeiTrigger2"
   class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
  <property name="jobDetail" ref="hitBeibeiJob"/>
  <property name="cronExpression" value="0/30 * * * * ?"/>
  </bean>

 

5,初始化 org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean

  concurrent属性:true/false;参考 https://www.cnblogs.com/seeall/p/12084778.html

  <bean id="hitBeibeiJob"
   class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  <property name="targetObject" ref="hitBeibeiScheduler"/>
  <property name="targetMethod" value="hit"/>
  <property name="concurrent" value="true"/>
  </bean>

 

6,hitBeibeiScheduler bean介绍

/**
* 用于测试定时任务:spring+quartz
*
* @author 88424581
* date 2019/12/23
*/
@Service(value = "hitBeibeiScheduler")
public class HitBeibeiScheduler implements ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory.getLogger(HitBeibeiScheduler.class);

private ApplicationContext applicationContext;

// 执行job
public void hit() throws InterruptedException {
LOGGER.info("现在时间是" + DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss") + ", 打贝贝...");
Thread.sleep(60000);
LOGGER.info("现在时间是" + DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")
+ ", 过去了60秒...");
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}


  



 


以上是关于sping+quartz定时任务的最简单实践的主要内容,如果未能解决你的问题,请参考以下文章

集群式Quartz定时任务框架实践

spring-boot Quartz 实践

spring-boot-starter-quartz集群实践

spring-boot-starter-quartz集群实践

spring-boot-starter-quartz集群实践

对quartz定时任务的初步认识