For the development of the game project of the compatriots, the timer this thing is certainly not unfamiliar, today, I used to make a small summary of the regular time! There is no specific implementation of the principle, but the list of the four of the more common use of the method, relatively, so long as the following examples of its example can be!
1 ImportJava.util.Calendar;2 Importjava.util.Date;3 ImportJava.util.Timer;4 ImportJava.util.TimerTask;5 6 Public classTimetest {7 Public Static voidMain (string[] args) {8 timer1 ();9 //Timer2 ();Ten //Timer3 (); One //timer4 (); A } - - //The first method: set the specified task tasks to execute schedule (timertask task, Date time) at specified times the Public Static voidtimer1 () { -Timer timer =NewTimer (); -Timer.schedule (NewTimerTask () { - Public voidrun () { +System.out.println ("-------set to specify task--------"); - } +}, 2000);//sets the time specified, here is 2000 milliseconds A } at - //The second method: Set the execution of a fixed delay peroid for the specified task tasks after specifying delay delays - //Schedule (timertask task, long delay, long period) - Public Static voidTimer2 () { -Timer timer =NewTimer (); -Timer.schedule (NewTimerTask () { in Public voidrun () { -System.out.println ("-------set to specify task--------"); to } +}, 1000, 5000); - } the * //The third method: Set the execution of the fixed frequency peroid of the specified task tasks after specifying the delayed delay. $ //scheduleatfixedrate (timertask task, long delay, long period)Panax Notoginseng Public Static voidTimer3 () { -Timer timer =NewTimer (); theTimer.scheduleatfixedrate (NewTimerTask () { + Public voidrun () { ASystem.out.println ("-------set to specify task--------"); the } +}, 1000, 2000); - } $ $ //Fourth method: Schedule the specified task to execute at a fixed rate period the specified time Firsttime begins to repeat. - //timer.scheduleatfixedrate (timertask task,date firsttime,long period) - Public Static voidtimer4 () { theCalendar Calendar =calendar.getinstance (); -Calendar.set (Calendar.hour_of_day, 12);//Control TimeWuyiCalendar.set (calendar.minute, 0);//Control Points theCalendar.set (Calendar.second, 0);//Control seconds - WuDate time = Calendar.gettime ();//The time to execute the task, here is today's 12:00:00 - AboutTimer timer =NewTimer (); $Timer.scheduleatfixedrate (NewTimerTask () { - Public voidrun () { -System.out.println ("-------set to specify task--------"); - } A}, time, 1000 * 60 * 60 * 24);//This setting will delay the execution of the daily fixed + } the}
4 ways to use timers in Java