用ScheduledExecutorService实现任务调度

ScheduledExecutorService实现任务调度,定时循环执行

代码如下:

package com.shentong.limitcsv;

import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExecutorTest {
	private static final long DAY_TIMES = 5*60*1000;

	public static void scheduleAtFixedRate(Runnable runnable, int day, int hour, int min) throws Exception {
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
		long curLong = System.currentTimeMillis();
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(curLong);
		calendar.add(Calendar.DAY_OF_MONTH, day);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MINUTE, min);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		long delay=calendar.getTimeInMillis() - curLong;
		executor.scheduleAtFixedRate(runnable, delay, DAY_TIMES,
				TimeUnit.MILLISECONDS);
	}
	static Logger logger = LoggerFactory.getLogger(ExecutorTest.class);
	public static void main(String[] args) {		
		Exec manage = new Exec();
		try {
			scheduleAtFixedRate(manage, 0, 17, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}				
	}
}
class Exec implements Runnable{
	Logger logger = LoggerFactory.getLogger(Exec.class);
	static int cnt = 1;
	boolean taskstatus = false;
	@Override
	public void run() {
		logger.debug("执行了"+(cnt++)+"次");
		taskstatus = true;
		
	}
	public boolean isTaskstatus() {
		return taskstatus;
	}
	
}



你可能感兴趣的:(工作经验)