淺析spring定時器的使用
原生的Java定時器
使用Java.util包下的定時器也很簡單,具體代碼如下:
//設(shè)置定時器開始時間Date time = sdf.parse('2020-10-01 16:40:00');//設(shè)置定時器Timer timer = new Timer();//第三個參數(shù)表示每隔多久循環(huán)一次timer.schedule(new TimerTask() { @Override public void run() { System.out.println('嗨'); }}, time, 3000);
Spring的定時器
1)導(dǎo)包,除了spring提供的包之外,還需要quartz包(可以到maven倉庫中去下載) 2)自定義Task類:當(dāng)定時器啟動時,Spring執(zhí)行我們指定Task中的方法
3)MethodInvokingJobDetailFactoryBean類:將自定義的Task類交給MethodInvokingJobDetailFactoryBean,并告訴它Task的執(zhí)行方法,由它負(fù)責(zé)去執(zhí)行
4)CronTriggerFactoryBean觸發(fā)器:定義定時器觸發(fā)的時間,以及執(zhí)行對象
5)SchedulerFactoryBean:將觸發(fā)器對象交給它統(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 '><!-- 定時器--> <bean class='com.cjh.MyTask'></bean> <!-- 創(chuàng)建一個Spring提供好的計(jì)時器對象,用來做倒計(jì)時管控--> <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ā)器對象的容器--> <bean class='org.springframework.scheduling.quartz.SchedulerFactoryBean'> <property name='triggers'> <list><ref bean='cronTrigger'/> </list> </property> </bean></beans> 6)主函數(shù)
只需要加載配置文件,觸發(fā)器就會啟動
public class TestMain { public static void main(String[] args) throws MessagingException, ParseException { ApplicationContext context = new ClassPathXmlApplicationContext('ApplicationContext.xml'); }}
以上就是淺析spring定時器的使用的詳細(xì)內(nèi)容,更多關(guān)于spring 定時器的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Docker 容器健康檢查機(jī)制2. CSS3實(shí)現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效3. vue 獲取url參數(shù)、get參數(shù)返回?cái)?shù)組的操作4. vue開發(fā)chrome插件,實(shí)現(xiàn)獲取界面數(shù)據(jù)和保存到數(shù)據(jù)庫功能5. php判斷一個請求是ajax請求還是普通請求的方法6. Android View 事件防抖的兩種方案7. php實(shí)現(xiàn)斷點(diǎn)續(xù)傳大文件示例代碼8. python構(gòu)造IP報(bào)文實(shí)例9. JavaScript實(shí)現(xiàn)可拖拽的進(jìn)度條10. python datetime時間格式的相互轉(zhuǎn)換問題
