java中ScheduledExecutorService实现定时任务

该类需要导入包

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

一、使用scheduleAtFixedRate()方法实现周期性执行

public class ScheduledExecutorServiceTest {
    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("run "+ System.currentTimeMillis());
            }
        }, 0, 100, TimeUnit.MILLISECONDS);
    }
}

每隔100毫秒,执行一次run任务,得到执行后的打印:

run 1501051231331
run 1501051231427
run 1501051231527
run 1501051231628
run 1501051231726
run 1501051231827
run 1501051231926
run 1501051232026
run 1501051232127
.......

接口scheduleAtFixedRate原型定义及参数说明

 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
				long initialDelay,
				long period,
				TimeUnit unit);

command:执行线程
initialDelay:初始化延时
period:两次开始执行最小间隔时间
unit:计时单位

接口scheduleWithFixedDelay原型定义及参数说明

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
				long initialDelay,
				long delay,
				TimeUnit unit);

command:执行线程
initialDelay:初始化延时
period:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
unit:计时单位

周期定时执行某个任务。

有时候我们希望一个任务被安排在凌晨3点(访问较少时)周期性的执行一个比较耗费资源的任务,可以使用下面方法设定每天在固定时间执行一次任务。

/**
 * 每天晚上8点执行一次
 * 每天定时安排任务进行执行
 */
public static void executeEightAtNightPerDay() {
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
	long oneDay = 24 * 60 * 60 * 1000;
	long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();
	initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
 
	executor.scheduleAtFixedRate(
			new EchoServer(),
			initDelay,
			oneDay,
			TimeUnit.MILLISECONDS);
}
/**
 * 获取指定时间对应的毫秒数
 * @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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章