一. 前言
最近在公司的項(xiàng)目中用到了定時(shí)任務(wù), 本篇博文將會(huì)對(duì)TimerTask定時(shí)任務(wù)進(jìn)行總結(jié), 其實(shí)TimerTask在實(shí)際項(xiàng)目中用的不多,
因?yàn)樗荒茉谥付〞r(shí)間運(yùn)行, 只能讓程序按照某一個(gè)頻度運(yùn)行.
二. TimerTask
JDK中Timer是一個(gè)定時(shí)器類(lèi), 它可以為指定的定時(shí)任務(wù)進(jìn)行配置.
JDK中TimerTask是一個(gè)定時(shí)任務(wù)類(lèi), 該類(lèi)實(shí)現(xiàn)了Runnable接口, 是一個(gè)抽象類(lèi), 我們可以繼承這個(gè)類(lèi), 實(shí)現(xiàn)定時(shí)任務(wù).
/** * 繼承TimerTask實(shí)現(xiàn)定時(shí)任務(wù) */ public class MyTask extends TimerTask { @Override public void run() { String currentTime = new SimpleDateFormat("yyy-MM-dd hh:mm:ss").format(new Date()); System.out.println(currentTime + " 定時(shí)任務(wù)正在執(zhí)行..."); } public static void main(String[] args) { Timer timer = new Timer(); // 1秒鐘執(zhí)行一次的任務(wù), 參數(shù)為: task, delay, peroid timer.schedule(new MyTask(), 2000, 1000); } } 三. 整合Spring
兩個(gè)核心類(lèi): ScheduledTimerTask, TimerFactoryBean
ScheduledTimerTask類(lèi)是對(duì)TimerTask的包裝器實(shí)現(xiàn), 通過(guò)該類(lèi)可以為這個(gè)任務(wù)定義觸發(fā)器信息.
TimerFactoryBean類(lèi)可以讓Spring使用配置創(chuàng)建觸發(fā)器, 并為一組指定的ScheduledTimerTask bean自動(dòng)創(chuàng)建Timer實(shí)例.
1. 引入Jar包: spring.jar, commons-logging.jar
2. 定時(shí)調(diào)度業(yè)務(wù)類(lèi):
/** * 定時(shí)調(diào)度業(yè)務(wù)類(lèi) */ public class TaskService extends TimerTask { private int count = 1; public void run() { System.out.println("第" + count + "次執(zhí)行定時(shí)任務(wù)"); count++; } } 3. 核心配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="taskService" class="com.zdp.service.TaskService"></bean> <bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <property name="timerTask" ref="taskService" /> <!-- 每隔一天執(zhí)行一次配置: 24*60*60*1000 --> <!-- 每1秒鐘程序執(zhí)行一次 --> <property name="period" value="1000" /> <!-- 程序啟動(dòng)4秒鐘后開(kāi)始執(zhí)行 --> <property name="delay" value="4000" /> </bean> <bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <ref bean="scheduledTimerTask" /> </list> </property> </bean> </beans>
4. 測(cè)試類(lèi):
public class Main { public static void main(String[] args) { // 加載spring配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println("<<-------- 啟動(dòng)定時(shí)任務(wù) -------- >>"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { try { if (reader.readLine().equals("quit")) { System.out.println("<<-------- 退出定時(shí)任務(wù) -------- >>"); System.exit(0); } } catch (IOException e) { throw new RuntimeException("error happens...", e); } } } } 以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注