入门
public class Time01 { public static void main(String[] args) { // Timer timer01=new Timer(); // timer01.schedule(new TimerTask(){ // // @Override // public void run() { // // System.out.println("bombing"); // }}, 1000); new Timer().schedule(new TimerTask() { @Override public void run() { System.out.println("bombing"); } }, 10000); while (true) { System.out.println(new Date().getSeconds()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
运行结果
21
22
23
24
25
26
27
28
29
30
bombing
31
32
33
连续执行
public class Time02 { public static void main(String[] args) { new Timer().schedule(new TimerTask() { @Override public void run() { System.out.println("bombing"); } }, 10000,3000); //每隔3秒执行 while (true) { System.out.println(new Date().getSeconds()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
运行结果:
50
51
52
53
54
55
56
57
58
59
bombing
0
1
2
bombing
3
4
5
bombing
6
7
提高
匿名内部类是临时的
整数分为奇数和偶数,所以可以按照奇偶操作完成
/** *一个2秒执行,另一个4秒执行,交替循环往复 * */ public class Time03 { static int i = 0; // 静态变量可以记录类创建的对象数量 public static void main(String[] args) { class MyTimerTask extends TimerTask { //内部类内部不能生成静态变量 public void run() { i=(i+1)%2; System.out.println("bombing"); new Timer().schedule(new MyTimerTask(), 2000+2000*i); } } new Timer().schedule(new MyTimerTask(), 2000); while (true) { try { System.out.println(new Date().getSeconds()); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
运行结果:
13
14
bombing
15
16
17
18
bombing
19
20
bombing
21
22
23
24
bombing
25
/** * 每天在指定的时间执行操作 * 提供调度需求的开源框架Quartz在这方面处理能力很强 */ public class Timer04 { public static void main(String[] args) { String str = "2011-08-28 08:39:00"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Timer timer = new Timer(); try { timer.schedule(new TimerTask() { @Override public void run() { System.out.println("timer"); } }, sdf.parse(str), 24 * 60 * 1000); } catch (ParseException e) { e.printStackTrace(); } while (true) { System.out.println(new Date().getSeconds()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 * 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 timer 0 1 2 3 4 5 */ }