使用quartz和spring自动调度。
具体实现bean:
package com.duduli.li.quartz;
import java.util.Date;
public class Display {
@SuppressWarnings("deprecation")
public void disp(){
System.out.println(new Date().getSeconds());
System.out.println("自动控制测试");
}
}
继承quartzjobbean类:这个类和继承Timer类类似
。
package com.duduli.li.quartz;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class AutoRun extends QuartzJobBean{
private Display display;
public void setDisplay(Display display) {
this.display = display;
}
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
display.disp();
}
}
spring配置文件:
<!-- quartz进行自动调度 -->
<!-- 具体实现类 -->
<bean id="display2" class="com.duduli.li.quartz.Display"></bean>
<!-- spring对quartz的支持,Auto类实现quartz的job接口的类,jobDataAsMap是将实现类注入其中 -->
<bean id="quartz" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.duduli.li.quartz.AutoRun"/>
<property name="jobDataAsMap">
<map>
<entry key="display" value-ref="display2"></entry>
</map>
</property>
</bean>
<!-- spring对quartz的支持,对其值的设定 -->
<bean id="simpleTask" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="quartz"></property>
<property name="startDelay" value="2000"></property>
<property name="repeatInterval" value="2000"></property>
</bean>
<!-- 启动自动调度 -->
<bean id="quartzTest" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="simpleTask"/>
</list>
</property>
</bean>
client调用:
package com.duduli.li.quartz;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
factory.getBean("quartzTest");
}
}