Java定时任务
import java.util.Timer;
import java.util.TimerTask;
/**
* 定时任务demo
*/
public class TestTimerTask {
static class NotifyTask extends TimerTask {
int retryTimes;
int curTimes = 0;
Timer t;
public NotifyTask(Timer t, int retryTimes) {
this.t = t;
this.retryTimes = retryTimes;
}
@Override
public void run() {
System.out.println("第" + curTimes + "次执行");
if (++curTimes > retryTimes - 1) {
System.out.println("达到次数上限,结束任务!");
t.cancel();
t.purge();
}
}
}
public static void main(String[] args) {
Timer t = new Timer();
// 最多重试5次
TimerTask task = new NotifyTask(t, 5);
// 延迟5秒,每隔2秒执行一次
t.schedule(task, 5000, 2000);
}
}
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
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
Last Updated: 2023/01/30, 11:01:00