淺析spring定時器的使用
原生的Java定時器
使用Java.util包下的定時器也很簡單,具體代碼如下:
//設置定時器開始時間Date time = sdf.parse('2020-10-01 16:40:00');//設置定時器Timer timer = new Timer();//第三個參數(shù)表示每隔多久循環(huán)一次timer.schedule(new TimerTask() { @Override public void run() { System.out.println('嗨'); }}, time, 3000);
Spring的定時器
1)導包,除了spring提供的包之外,還需要quartz包(可以到maven倉庫中去下載) 2)自定義Task類:當定時器啟動時,Spring執(zhí)行我們指定Task中的方法
3)MethodInvokingJobDetailFactoryBean類:將自定義的Task類交給MethodInvokingJobDetailFactoryBean,并告訴它Task的執(zhí)行方法,由它負責去執(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提供好的計時器對象,用來做倒計時管控--> <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定時器的使用的詳細內(nèi)容,更多關于spring 定時器的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
1. Java源碼解析之接口List2. Java xml數(shù)據(jù)格式返回實現(xiàn)操作3. python讀取中文路徑時出錯(2種解決方案)4. XML入門精解之結(jié)構(gòu)與語法5. Python加載數(shù)據(jù)的5種不同方式(收藏)6. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼7. Python用K-means聚類算法進行客戶分群的實現(xiàn)8. layui Ajax請求給下拉框賦值的實例9. python編寫五子棋游戲10. python mysql 字段與關鍵字沖突的解決方式
