quartz 添加定时任务
最近都在做API接口,发现有些接口没办法长期跟踪,但是有经常出错,所以需要做监控,本来这个网络运维也可以做的,但是发现java里面也有很好的方法,最终决定还是在java里面实现。不多说,直接上代码。
a.首先就是创建一个quartz-config.xml,里面配置需要启动的类以及方法,定时的时间。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 要调用验卡的工作类 -->
<bean id="sendChannel" class="main.java.ssm.sendchannel.controller.SendChannelController"></bean>
<!-- 定义调用对象和调用对象的方法 -->
<bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 调用的类 -->
<property name="targetObject">
<ref bean="sendChannel"/>
</property>
<!-- 调用类中的方法 -->
<!-- <property name="targetMethod">
<value>work</value>
</property> -->
<property name="targetMethod">
<value>verifyInfo</value>
</property>
</bean>
<!-- 定义触发时间 -->
<bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<ref bean="jobtask"/>
</property>
<!-- cron表达式 -->
<property name="cronExpression">
<value>0 0/30 * * * ?</value>
</property>
</bean>
<!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
<bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="doTime"/>
</list>
</property>
</bean>
</beans>
b.接着就在web.xml配置quartz-config.xml的调用
<!-- 配置上游接口监控 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/quartz-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
c.重要的就是方法的格式,lz发现方法有返回值的话是没有办法调用成功的,希望有大牛能解决。……——……
public class SendChannelController
{
public void verifyInfo()
{
log.info("Quartz的任务调度!!!");
}
}
d.到这里所有的代码都写好了,当然需要测试!!!
public static void main(String[] args)
{
System.out.print("Test start.");
ApplicationContext context = new ClassPathXmlApplicationContext("spring/quartz-config.xml");
//如果配置文件中将startQuertz bean的lazy-init设置为false 则不用实例化
//context.getBean("startQuertz");
System.out.print("Test end..\n");
}
e.测试结果一切正常,可以启动服务了。这时定时器就可以随服务一起启动了。

浙公网安备 33010602011771号