java定时任务

该处介绍的是 ScheduledExecutorService定时周期性执行指定任务


ScheduleExecutorService接口中有四个重要的方法,实现定时任务常用的方法是:

scheduleAtFixedRate和scheduleWithFixedDelay。

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

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,  
            long initialDelay,  
            long period,  
            TimeUnit unit);  
command:执行线程
initialDelay:初始化延时
period:固定时间间隔(两次开始执行最小间隔时间
unit:计时单位

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

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,  
                long initialDelay,  
                long delay,  
                TimeUnit unit);  
command:执行线程
initialDelay:初始化延时
period:相对时间间隔(前一次执行结束到下一次执行开始的间隔时间
unit:计时单位

两个方法的区别:主要在于时间间隔。第一个的任务执行,到达固定的时间间隔,就会开始执行新的任务,但是,有一种情况必须注意,当任务的执行时间大于规定的间隔时间时,并不会开辟新的线程执行新的任务,而是等待任务结束之后立即执行新的任务,这点格外注意。第二个的任务执行,无论任务执行多久,前一次任务必须执行结束之后,等待时间间隔之后再执行新的任务。第二种比较常用,相对比较简单。

实例:

1.按指定频率周期执行某个任务(scheduleAtFixedRate)

初始化延迟0ms开始执行,每隔100ms重新执行一次任务

/** 
 * 以固定周期频率执行任务 
 */  
public static void executeFixedRate() {  
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  //也可用Executors.newSingleThreadScheduledExecutor();
    executor.scheduleAtFixedRate(
    new Runnable() {
	@Override
	public void run() {
		//线程执行任务
	}
    },  
    0,  
    100,  
    TimeUnit.MILLISECONDS);  
} 
间隔指的是连续两次任务执行的开始时间的间隔

2.按指定频率间隔执行某个任务(scheduleWithFixedDelay)

初始化时延时0ms开始执行,本次执行结束后延迟100ms开始下次执行。

/** 
 * 以固定时间间隔执行任务 
 */  
public static void executeFixedRate() {  
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
    executor.scheduleWithFixedRate(
    new Runnable() {
	@Override
	public void run() {
		//线程执行任务
	}
    },  
    0,  
    100,  
    TimeUnit.MILLISECONDS);  
} 

应用场景例子:

/** 
 * 每天晚上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;  
}  


class EchoServer implements Runnable {  
    @Override  
    public void run() {  
        try {  
            Thread.sleep(50);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        System.out.println("This is a echo server. The current time is " +  
                System.currentTimeMillis() + ".");  
    }  
}  




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值