淺析spring定時器的使用
原生的Java定時器
使用Java.util包下的定時器也很簡單,具體代碼如下:
//設置定時器開始時間Date time = sdf.parse('2020-10-01 16:40:00');//設置定時器Timer timer = new Timer();//第三個參數表示每隔多久循環一次timer.schedule(new TimerTask() { @Override public void run() { System.out.println('嗨'); }}, time, 3000);
Spring的定時器
1)導包,除了spring提供的包之外,還需要quartz包(可以到maven倉庫中去下載) 2)自定義Task類:當定時器啟動時,Spring執行我們指定Task中的方法
3)MethodInvokingJobDetailFactoryBean類:將自定義的Task類交給MethodInvokingJobDetailFactoryBean,并告訴它Task的執行方法,由它負責去執行
4)CronTriggerFactoryBean觸發器:定義定時器觸發的時間,以及執行對象
5)SchedulerFactoryBean:將觸發器對象交給它統一保管
配置信息如下:
<?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> <!-- 創建一個Spring提供好的計時器對象,用來做倒計時管控--> <bean class='org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean'> <property name='targetObject' ref='myTask'/> <property name='targetMethod' value='test'/> </bean> <!-- 觸發器--> <bean class='org.springframework.scheduling.quartz.CronTriggerFactoryBean'> <property name='jobDetail' ref='taskExecutor'/> <property name='cronExpression' value='30/5 41 18 * * ?'/> </bean> <!-- 管理觸發器對象的容器--> <bean class='org.springframework.scheduling.quartz.SchedulerFactoryBean'> <property name='triggers'> <list><ref bean='cronTrigger'/> </list> </property> </bean></beans> 6)主函數
只需要加載配置文件,觸發器就會啟動
public class TestMain { public static void main(String[] args) throws MessagingException, ParseException { ApplicationContext context = new ClassPathXmlApplicationContext('ApplicationContext.xml'); }}
以上就是淺析spring定時器的使用的詳細內容,更多關于spring 定時器的資料請關注好吧啦網其它相關文章!
相關文章:
