java 定時執行
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TestTimer {
static int count = 0;
public static void showTimer() {
TimerTask task = new TimerTask() {
@Override
public void run() {
++count;
System.out.println("時間=" + new Date() + " 執行了" + count + "次"); // 1次
}
};
//設定執行時間
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
//定製每天的21:09:00執行,
calendar.set(year, month, day, 00, 00, 00);
Date date = calendar.getTime();
Timer timer = new Timer();
System.out.println(date);
int period = 5 * 1000;
//每天的date時刻執行task,每隔2秒重複執行
// timer.schedule(task, date, period);
//每天的date時刻執行task, 僅執行一次
timer.schedule(task, date);
}
public static void main(String[] args) {
showTimer();
}
}