Java定時器(二)之Spring定時任務、Quartz實現
阿新 • • 發佈:2019-01-01
使用基於註解配置的spring定時器
基於註解會相對簡單的多,直接編寫任務類Mytask
@EnableScheduling
@Component
public class Mytask {
@Scheduled(cron = "*/5 * * * * ?")
public void execute(){
System.out.println("基於註解配置的spring定時任務!");
}
}
任務類也要納入spring管理
<context:component-scan base-package="com.simonsfan.study.controller.Mytask"> <task:annotation-driven/>
使用基於xml配置的spring定時器
public class MyTask {
public void execute(){
System.out.println("基於註解配置的spring定時任務!");
}
}
編寫個spring-task.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:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd" default-lazy-init="true"> <task:scheduled-tasks> <!--直充重試機制--> <task:scheduled ref="myTask" method="execute" cron="0 1 * * * ?"/> ##myTask必須是定時任務類名小寫 </task:scheduled-tasks> </beans>
並把此加入spring配置檔案中
<!-- task -->
<import resource="spring-task.xml"/>
quartz定時器
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.2</version>
</dependency>
@Component public class Mytask { public void execute() { System.out.println("基於spring+quartz實現定時任務!");; } }
spring配置檔案中加入
<bean id="jobBean" class="com.pptv.vipbackend.controller.Mytask"/>
<bean id="myJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="jobBean"/>
</property>
<property name="targetMethod">
<value>execute</value><!--任務類中的方法名-->
</property>
<!--將併發設定為false-->
<property name="concurrent" value="false" />
</bean>
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="myJobDetail" />
<property name="startDelay" value="1000" />
<property name="repeatInterval" value="2000" />
</bean>
<!-- 總管理類如果將lazy-init='false'那麼容器啟動就會執行排程程式 -->
<bean id="startQuertz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false" autowire="no">
<property name="triggers">
<list>
<!--作業排程器,list下可加入其他的排程器-->
<ref bean="simpleTrigger" />
</list>
</property>
</bean>
這樣,基於spring + quartz便可實現定時任務的排程。
---------------------------------------------------------------------------廣告時間-----------------------------------------------------------------------
關注微信公眾號:91電影社,裡面分享最新最熱電影、韓劇、美劇,持續更新……