HeLei Blog

java-timer

使用Timer类实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class TimerTest {
public static String getStringDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
public static void main(String[] args) throws InterruptedException {
final TimerTask timerTask1 = new TimerTask() {
@Override
public void run() {
try {
System.out.println("task2 invoked!"+Thread.currentThread().getId());
System.out.println("begin: "+getStringDate());
//Thread.sleep(5000L);
} catch (Exception e) {
e.printStackTrace();
}
}
};
final TimerTask timerTask2 = new TimerTask() {
@Override
public void run() {
try {
System.out.println("task2 invoked!"+Thread.currentThread().getId());
System.out.println("begin: "+getStringDate());
//Thread.sleep(5000L);
} catch (Exception e) {
e.printStackTrace();
}
}
};
Timer timer = new Timer();// 实例化Timer
timer.schedule(timerTask1, 8000);
timer.schedule(timerTask2, 10000);
}
}

Timer

1
2

坚持原创技术分享,您的支持将鼓励我继续创作!