Spring + Quartz implement timer
Links to related articles:
IDEA uses Maven to build SSM framework web projects
Tips before viewing:
The IDEA version used in this article is ultimate 2019.1, the JDK version is 1.8.0_141, and the Tomcat version is 9.0.12.
The jar package version used in this article is springframework4.3.18.RELEASE and quartz2.3.2.
Timer class Timer.java
package com.example.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Timer {
public void TimerTask(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("定时任务,时间为:" + sdf .format(new Date()));
}
}
The timer part of applicationContext.xml is configured as
<bean name="task" class="com.example.controller.Timer"/>
<bean id="taskDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 执行的类 -->
<property name="targetObject" ref="task"/>
<!-- 执行的类中的方法 -->
<property name="targetMethod" value="TimerTask"/>
</bean>
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="taskDetail"/>
<!-- 每一秒钟执行一次 -->
<property name="cronExpression" value="0/1 * * * * ?">
</property>
</bean>
<!-- 总配置 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!-- 添加触发器 -->
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
Start the service, the operation effect is as shown below