淺析spring定時(shí)器的使用
原生的Java定時(shí)器
使用Java.util包下的定時(shí)器也很簡單,具體代碼如下:
//設(shè)置定時(shí)器開始時(shí)間Date time = sdf.parse('2020-10-01 16:40:00');//設(shè)置定時(shí)器Timer timer = new Timer();//第三個(gè)參數(shù)表示每隔多久循環(huán)一次timer.schedule(new TimerTask() { @Override public void run() { System.out.println('嗨'); }}, time, 3000);
Spring的定時(shí)器
1)導(dǎo)包,除了spring提供的包之外,還需要quartz包(可以到maven倉庫中去下載) 2)自定義Task類:當(dāng)定時(shí)器啟動(dòng)時(shí),Spring執(zhí)行我們指定Task中的方法
3)MethodInvokingJobDetailFactoryBean類:將自定義的Task類交給MethodInvokingJobDetailFactoryBean,并告訴它Task的執(zhí)行方法,由它負(fù)責(zé)去執(zhí)行
4)CronTriggerFactoryBean觸發(fā)器:定義定時(shí)器觸發(fā)的時(shí)間,以及執(zhí)行對(duì)象
5)SchedulerFactoryBean:將觸發(fā)器對(duì)象交給它統(tǒng)一保管
配置信息如下:
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd '><!-- 定時(shí)器--> <bean class='com.cjh.MyTask'></bean> <!-- 創(chuàng)建一個(gè)Spring提供好的計(jì)時(shí)器對(duì)象,用來做倒計(jì)時(shí)管控--> <bean class='org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean'> <property name='targetObject' ref='myTask'/> <property name='targetMethod' value='test'/> </bean> <!-- 觸發(fā)器--> <bean class='org.springframework.scheduling.quartz.CronTriggerFactoryBean'> <property name='jobDetail' ref='taskExecutor'/> <property name='cronExpression' value='30/5 41 18 * * ?'/> </bean> <!-- 管理觸發(fā)器對(duì)象的容器--> <bean class='org.springframework.scheduling.quartz.SchedulerFactoryBean'> <property name='triggers'> <list><ref bean='cronTrigger'/> </list> </property> </bean></beans> 6)主函數(shù)
只需要加載配置文件,觸發(fā)器就會(huì)啟動(dòng)
public class TestMain { public static void main(String[] args) throws MessagingException, ParseException { ApplicationContext context = new ClassPathXmlApplicationContext('ApplicationContext.xml'); }}
以上就是淺析spring定時(shí)器的使用的詳細(xì)內(nèi)容,更多關(guān)于spring 定時(shí)器的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Laravel操作session和cookie的教程詳解2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. XML入門的常見問題(一)4. css進(jìn)階學(xué)習(xí) 選擇符5. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法6. PHP字符串前后字符或空格刪除方法介紹7. jsp實(shí)現(xiàn)登錄界面8. 解析原生JS getComputedStyle9. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式10. Echarts通過dataset數(shù)據(jù)集實(shí)現(xiàn)創(chuàng)建單軸散點(diǎn)圖
