import?java.util.Calendar;import?java.util.Date;import?java.util.Timer;import?java.util.TimerTask;?public?class?TimeTest?{??public?static?void?main(String[]?args)?{????timer1();????//timer2();????//timer3();????//timer4();??}???//?第一種方法:設(shè)定指定任務(wù)task在指定時(shí)間time執(zhí)行?schedule(TimerTask?task,?Date?time)??public?static?void?timer1()?{????Timer?timer?=?new?Timer();????timer.schedule(new?TimerTask()?{??????public?void?run()?{????????System.out.println("-------設(shè)定要指定任務(wù)--------");??????}????},?2000);//?設(shè)定指定的時(shí)間time,此處為2000毫秒??}???//?第二種方法:設(shè)定指定任務(wù)task在指定延遲delay后進(jìn)行固定延遲peroid的執(zhí)行??//?schedule(TimerTask?task,?long?delay,?long?period)??public?static?void?timer2()?{????Timer?timer?=?new?Timer();????timer.schedule(new?TimerTask()?{??????public?void?run()?{????????System.out.println("-------設(shè)定要指定任務(wù)--------");??????}????},?1000,?5000);??}???//?第三種方法:設(shè)定指定任務(wù)task在指定延遲delay后進(jìn)行固定頻率peroid的執(zhí)行。??//?scheduleAtFixedRate(TimerTask?task,?long?delay,?long?period)??public?static?void?timer3()?{????Timer?timer?=?new?Timer();????timer.scheduleAtFixedRate(new?TimerTask()?{??????public?void?run()?{????????System.out.println("-------設(shè)定要指定任務(wù)--------");??????}????},?1000,?2000);??}?????//?第四種方法:安排指定的任務(wù)task在指定的時(shí)間firstTime開(kāi)始進(jìn)行重復(fù)的固定速率period執(zhí)行.??//?Timer.scheduleAtFixedRate(TimerTask?task,Date?firstTime,long?period)??public?static?void?timer4()?{????Calendar?calendar?=?Calendar.getInstance();????calendar.set(Calendar.HOUR_OF_DAY,?12);?//?控制時(shí)????calendar.set(Calendar.MINUTE,?0);????//?控制分????calendar.set(Calendar.SECOND,?0);????//?控制秒?????Date?time?=?calendar.getTime();?????//?得出執(zhí)行任務(wù)的時(shí)間,此處為今天的12:00:00?????Timer?timer?=?new?Timer();????timer.scheduleAtFixedRate(new?TimerTask()?{??????public?void?run()?{????????System.out.println("-------設(shè)定要指定任務(wù)--------");??????}????},?time,?1000?*?60?*?60?*?24);//?這里設(shè)定將延時(shí)每天固定執(zhí)行??}}
以上就是北大青鳥長(zhǎng)沙麓谷校區(qū)java培訓(xùn)機(jī)構(gòu)的小編針對(duì)“Java技術(shù)分享,timer定時(shí)的四種方法”的內(nèi)容進(jìn)行的回答,希望對(duì)大家有所幫助,如有疑問(wèn),請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。