Spring下對Quartz的使用

      學Spring中接觸了Quartz(計劃任務調度框架),測試成功後,將簡單代碼保存在此。


首先導入 log4j quartz slf4j  JAR包

package Text;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class MyJob extends QuartzJobBean{
private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	@Override
	protected void executeInternal(JobExecutionContext context)
			throws JobExecutionException {
		// TODO Auto-generated method stub
	    String s = (String) context.getJobDetail().getJobDataMap().get("studentName");
		String now=sdf.format(new Date());
		System.out.println(s+"在"+now+"執行了計劃任務");
		}
}

<pre name="code" class="java">package Text;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Text {
public static void main(String[] args) {
	ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

}
}

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="myJobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="Text.MyJob"></property>
<property name="jobDataMap">
<map>
<entry key="studentName"  value="王小強"></entry>
</map>
</property>
</bean>
<!--這是簡單的時間使用框架 
<bean id="myTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="myJobDetail"></property> 
<property name="startTime">
<bean class="java.util.Date"></bean>
</property>
<property name="repeatInterval" value="3000"></property>
<property name="repeatCount" value="3"></property>
</bean>
 -->
 <!-- 這是複雜的時間使用框架 -->
<bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="myJobDetail"></property> 
<property name="cronExpression" value="* * 17 * * ?"></property>
</bean>
 
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list><ref bean="myTrigger"/> </list>
</property>
</bean>
</beans>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章