Timer myTimer;
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
public void run() {
// Do some thing
}
}, 0, 1000);
ในการกำหนดเวลาหน่วยเท่ากับ 1000 = 1 วินาที
Timer Stop/Cancel
myTimer.cancel();
Example การใช้ Timer บนภาษา Java แบบง่าย ๆ
MyClass.java
package com.java.myapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class MyWindowsForm {
public static void main(String[] args) {
Timer myTimer;
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
public void run() {
timerTick();
}
}, 0, 1000);
}
private static void timerTick() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
System.out.println("Time now : " + formattedDate);
}
}
Output
Time now : 2013-08-07 13:07:05
Time now : 2013-08-07 13:07:06
Time now : 2013-08-07 13:07:07
Time now : 2013-08-07 13:07:08
Time now : 2013-08-07 13:07:09
Time now : 2013-08-07 13:07:10
Time now : 2013-08-07 13:07:11
Time now : 2013-08-07 13:07:12
Time now : 2013-08-07 13:07:13
Time now : 2013-08-07 13:07:14
Time now : 2013-08-07 13:07:15
Time now : 2013-08-07 13:07:16
Time now : 2013-08-07 13:07:17
Time now : 2013-08-07 13:07:18
Time now : 2013-08-07 13:07:19
.
.
.