最近在做项目时用到了定时器,使用Spring自带的监听器无法做到每周五或者每月每月月底定时执行,最终选择使用quartz做定时任务
在Spring xml配置文件中添加一下代码就可以了
<!-- 全部定义到内部bean中,可以添加多个任务 -->
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<!-- 调度任务01 周统计-->
<bean class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<bean class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 执行类 -->
<property name="targetObject">
<ref bean="taskWork" />
</property>
<!-- 类中要定时执行的方法 -->
<property name="targetMethod">
<value>GetCountWeek</value>
</property>
</bean>
</property>
<property name="cronExpression" value=" 0 0 18 ? * 1 "/>
</bean>
<!-- 调度任务02 月统计-->
<bean class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<bean class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="taskWork" />
</property>
<property name="targetMethod">
<value>GetCountMonth</value>
</property>
</bean>
</property>
<property name="cronExpression" value="0 59 18 L * ?"/>
</bean>
</list>
</property>
</bean>
<!-- 配置任务所在的类 -->
<bean id="taskWork" class="com.yuan.utils.SendCountOfWeek" />
然后在对应的类中编写要执行的方法
public class SendCountOfWeek { //周统计 public void GetCountWeek(){ System.out.println("这是第一个方法"); } //月统计 public void GetCountMonth(){
}}System.out.println("这是第二个方法");
刚开始配置bean class=org.springframework.scheduling.quartz.CronTriggerBean会在启动时报错,后来查询将其改为org.springframework.scheduling.quartz.CronTriggerFactoryBean
cron表达式查询:http://cron.qqe2.com/之后tomcat正常启动