java timer schedule_Java Timer schedule方法和scheduleAtFixedRate方法的区别

1. schedule() ,2个参数方法:

在执行任务时,如果指定的计划执行时间scheduledExecutionTime <= systemCurrentTime,则task会被立即执行。

2. schedule() ,3个参数方法:

在执行任务时,如果指定的计划执行时间scheduledExecutionTime <= systemCurrentTime,则task会被立即执行,之后按period参数固定重复执行。

3. scheduleAtFixedRate() ,3个参数方法:

在执行任务时,如果指定的计划执行时间scheduledExecutionTime<= systemCurrentTime,则task会首先按执行一次;然后按照执行时间、系统当前时间和period参数计算出过期该执行的次数,计算按照: (systemCurrentTime-scheduledExecutionTime)/period,再次执行计算出的次数;最后按period参数固定重复执行。

4. schedule() 和scheduleAtFixedRate()

schedule()方法更注重保持间隔时间的稳定。

scheduleAtFixedRate()方法更注重保持执行频率的稳定。

代码案例:

import java.util.Date;

import java.util.Timer;

public class TestTask {

/**

* @param args

*/

public static void main(String[] args){

Date crtTime = new Date();

long crt = crtTime.getTime();

Timer timer = new Timer();

// 在指定时间执行

CommonTask task1 = new CommonTask("【任务一】");

timer.schedule(task1, new Date(crt - 1000));

// schedule和scheduleAtFixedRate

CommonTask task11 = new CommonTask("【任务二】");

timer.schedule(task11, new Date(crt - 10 * 1000),1000);

CommonTask task12 = new CommonTask("【任务三】");

timer.schedule(task12, new Date(crt - 10 * 1000),1000);

// schedule和scheduleAtFixedRate

CommonTask task13 = new CommonTask("【任务四】");

timer.schedule(task13, new Date(crt + 2 * 1000),1000);

CommonTask task14 = new CommonTask("【任务五】");

timer.scheduleAtFixedRate(task14, new Date(crt + 2 * 1000),1000);

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值