java 定时周期任务

参考:http://www.fengyunxiao.cn

1. 在run方法里延迟

public class TestThread {
	public static void main(String[] args) {
		
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				while (true) {
					System.out.println("执行任务");
					
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		
		// 每秒执行一次任务
		Thread thread = new Thread(runnable);
		thread.start();
	}
}

 

2. 使用Timer类控制延迟

public static void main(String[] args) {
		
	TimerTask task = new TimerTask() {
		@Override
		public void run() {
			System.out.println("执行任务");
		}
	};
	
	Timer timer = new Timer();
	// 延迟n毫秒后执行,1000表示1秒
	// timer.schedule(task, 1000);
	
	// 延迟delay毫秒后执行,每period毫秒执行一次
	timer.schedule(task, 1000, 1000);
}

  

参考:http://www.fengyunxiao.cn

原文地址:https://www.cnblogs.com/zscc/p/9359714.html