java schedule service_java-并发-定时任务ScheduleExecutorService和spring用法

一. ScheduleExecutorService配置

说明

注意问题:

我们需要捕获最上层的异常,防止出现异常中止执行,导致周期性的任务不再执行。

如果执行的任务大于我们指定的执行间隔,比如scheduleAtFixedRate方法;当执行任务的时间大于我们指定的间隔时间时,等待任务执行完毕,再开启新的线程;

方法区别

scheduleAtFixedRate从上一个任务开始计算,频率固定;

scheduleWithFixedDealy从上一个任务结束时开始计算,频率不固定;

scheduleAtFixedRate

public ScheduledFuture> scheduleAtFixedRate(Runnable command,//执行线程

long initialDelay,//初始化延迟

long period,//两次执行最小间隔

TimeUnit unit);//计时单位

scheduleWithFixedDelay

public ScheduledFuture> scheduleWithFixedDelay(Runnable command, //执行线程

long initialDelay, //初始化延时

long delay, //前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)

TimeUnit unit); //

使用例子

例子1:以固定周期频率执行任务

public static void executeFixedRate() {

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

executor.scheduleAtFixedRate(

new EchoServer(),

0,

100,

TimeUnit.MILLISECONDS);

}

例子2:以固定延迟时间进行执行

public static void executeFixedDelay() {

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

executor.scheduleWithFixedDelay(

new EchoServer(),

0,

100,

TimeUnit.MILLISECONDS);

}

例子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);

}

//获取指定时间对应的毫秒数

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() + ".");

}

}

二. Spring配置

除了我们自己实现定时任务之外,我们可以使用Spring帮我们完成这样的事情。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值