JAVA中Timer定时器调度方法

java timer中的时间调度方法主要有:
schedule(TimerTask task, Date firstTime, long period)
          Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.

但是如果此时的firstTime小于(时间落后于)当前时间,那么
task会立即执行,在调试的时候不方便,因为程序一启动就开始执行了,或许还没有到任务的触发点。

schedule(TimerTask task, long delay, long period)
          Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.

如果采用设置delay时间的方法,则可以进行处理。
比如:设置执行时间为每天的13:50,如果启动的时候时间已经过了13:35,那么应该在明天的13:35进行执行。此时可以这样处理:
  1. Calendar cal = Calendar.getInstance();
  2.         cal.set(Calendar.HOUR_OF_DAY, 13);
  3.         cal.set(Calendar.MINUTE, 35);
  4.         //cal.add(Calendar.DAY_OF_MONTH, 1);
  5.         Date date = new Date();
  6.         date = cal.getTime();
  7.         
  8.         Date now = new Date();
  9.         long interval = date.getTime() - now.getTime();
  10.         //should exec in next day
  11.         if (interval < 0) {
  12.             cal.add(Calendar.DAY_OF_MONTH, 1);
  13.             date = cal.getTime();
  14.             interval = date.getTime() - now.getTime();
  15.         }       
  16.         System.out.println("the interval time is: " + interval);
  17.         //the exec time interval is 2 secs.
  18.         timer.schedule(echoTask, interval, 2 * 1000);
如果delay的时间为负数,会报异常,因此,Calendar添加一天。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值