Timer
1. Overview timer
Timer, you can set the thread execution at a time something or a certain time, every specified time interval repeatedly to do something;
2. Timer class
Timer class can implement thread scheduling tasks for the future and is performed in the background thread, you can schedule a task to perform, or repeated periodically;
java.util.Timer,详见: Class Hours ;
3. Constructor
Construction method
Explanation
Timer()
Constructs a timer
4. Members method
return value
Method name
Explanation
void
schedule(TimerTask task, long delay)
Schedule tasks specified execution after a specified delay
void
schedule(TimerTask task, long delay, long period)
Start after a specified delay, re-execute the tasks specified fixed delay execution
void
schedule(TimerTask task, Date time)
Schedules the specified task execution at a specified time
void
schedule(TimerTask task, Date firstTime, long period)
Starting at the specified time, to perform the specified task for repeated fixed-delay execution
5. Java Examples
import java. text. SimpleDateFormat;
import java. util. *;
public class Test {
public static void main ( String[ ] args) {
Timer t = new Timer ( ) ;
t. schedule ( new TimerTask ( ) {
@Override
public void run ( ) {
for ( int i = 10 ; i >= 0 ; i-- ) {
System. out. println ( "倒数:" + i) ;
try {
Thread. sleep ( 1000 ) ;
} catch ( Exception e) {
}
}
System. out. println ( "嘭......嘭......" ) ;
t. cancel ( ) ;
}
} , 2000 ) ;
Timer t2 = new Timer ( ) ;
t2. schedule ( new TimerTask ( ) {
@Override
public void run ( ) {
SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ;
System. out. println ( sdf. format ( new Date ( ) ) ) ;
}
} , 5000 , 1000 ) ;
Timer t3 = new Timer ( ) ;
Calendar c = new GregorianCalendar ( 2030 , 1 - 1 , 1 , 0 , 0 , 0 ) ;
Date d = c. getTime ( ) ;
t3. schedule ( new TimerTask ( ) {
@Override
public void run ( ) {
System. out. println ( "搜索全盘......" ) ;
}
} , d, 1000 * 3600 * 24 ) ;
}
}