成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

淺析spring定時(shí)器的使用

瀏覽:78日期:2023-08-10 15:15:51

原生的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)文章!

標(biāo)簽: Spring
相關(guān)文章: