ScheduledExecutorService 时间调度器用法

 

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class TestScheduledThread {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final ScheduledExecutorService scheduler = Executors
				.newScheduledThreadPool(2);
		final int MINTIME = 1000 * 60;

		final Runnable beeper = new Runnable() {
			int count = 0;

			public void run() {
				System.out.println(new Date() + " beep " + (++count));
			}
		};
		// 1秒钟后运行,并每隔2秒运行一次
		final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(
				beeper, 1, 5, SECONDS);
		
		// 2秒钟后运行,并每次在上次任务运行完后等待5秒后重新运行
		final ScheduledFuture beeperHandle2 = scheduler.scheduleWithFixedDelay(
				beeper, 2, 5, SECONDS);

		// 指定时间"21:35:00"执行
		final ScheduledFuture beeperHandle3 = scheduler.scheduleAtFixedRate(
				beeper, getExecutionTime("21:35:00", MINTIME * 60 * 24),
				MINTIME * 60 * 24, TimeUnit.MILLISECONDS);
		// 30秒后结束关闭任务,并且关闭Scheduler
		scheduler.schedule(new Runnable() {
			public void run() {
				beeperHandle.cancel(true);
				beeperHandle2.cancel(true);
				beeperHandle3.cancel(true);
				scheduler.shutdown();
			}
		}, 30, SECONDS);
	}

	private static long getExecutionTime(String exeTime, long exeInterval) {
		long initDelay = getTimeMillis(exeTime) - System.currentTimeMillis();
		initDelay = initDelay > 0 ? initDelay : exeInterval + initDelay;
		return initDelay;
	}

	/**
	 * 获取指定时间对应的毫秒数
	 * 
	 * @param time
	 *            "HH:mm:ss"
	 * @return
	 */
	private static long getTimeMillis(String time) {
		try {
			DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
			DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
			Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " "
					+ time);
			return curDate.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}
}

 

你可能感兴趣的:(定时器,调度器)