天天看點

java中的定時器_java中實作定時器的四種方法(轉載)

轉載java中實作定時器的方法,記錄友善檢視。

package com.wxltsoft.tool;

import org.junit.Test;

import java.util.Calendar;

import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

public class TimerUtil {

public static void main(String[] args) {

// timer1();

// timer2();

// timer3();

timer4();

}

public static void timer1(){

Timer nTimer = new Timer();

nTimer.schedule(new TimerTask() {

@Override

public void run() {

System.out.println("----設定要指定任務-----");

}

},2000);

}

public static void timer2() {

Timer timer = new Timer();

timer.schedule(new TimerTask() {

public void run() {

System.out.println("-------延遲5000毫秒,每1000毫秒執行一次--------");

}

}, 5000, 1000);

}

public static void timer3() {

Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {

public void run() {

System.err.println("-------延遲5000毫秒,每1000毫秒執行一次--------");

}

}, 5000, 1000);

}

public static void timer4() {

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.HOUR_OF_DAY, 17);

calendar.set(Calendar.MINUTE, 26);

calendar.set(Calendar.SECOND, 0);

Date time = calendar.getTime();

Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {

public void run() {

System.out.println("-------設定要指定任務--------");

}

}, time, 1000 * 60 * 60 * 24);// 這裡設定将延時每天固定執行

}

}