Summary of timers in java

There are four ways to implement timers in java:
1.
/**
	 * Delay 20000 milliseconds to execute java.util.Timer.schedule(TimerTask task, long delay)
	 */
	public static void timer1() {
		Timer nTimer = new Timer ();
		nTimer.schedule(new TimerTask() {
			public void run() {
				System.err.println("-------Set the task to be specified-------");
			}
		}, 2000);
	}

two,
/**
	 * java.util.Timer.schedule(TimerTask task, long delay)
	 */
	public static void timer2() {
		Timer timer = new Timer ();
		timer.schedule(new TimerTask() {
			public void run() {
				System.out.println("------- delay 5000 milliseconds, execute every 1000 milliseconds --------");
			}
		}, 5000, 1000);
	}

three,
/**
	 * java.util.Timer.schedule(TimerTask task, long delay)
	 */
	public static void timer3() {
		Timer timer = new Timer ();
		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				System.err.println("-------delay 5000ms, execute every 1000ms-------");
			}
		}, 5000, 1000);
	}

Four,

/**
	 * Set 17:56 to execute the task
	 * java.util.Timer.scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
	 */
	public static void timer4() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 17);
		calendar.set(Calendar.MINUTE, 56);
		calendar.set(Calendar.SECOND, 0);

		Date time = calendar.getTime();

		Timer timer = new Timer ();
		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				System.out.println("-------Set the task to be specified-------");
			}
		}, time, 1000 * 60 * 60 * 24);// This setting will delay the fixed execution every day
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326525530&siteId=291194637
Recommended