java 定时器10秒,java计时器任务计划

From reading on Stack Overflow I've seen that many of you don't recommend using Timer Task. Hmmm... but I already implemented this:

I have this code:

detectionHandlerTimer.schedule(myTimerTask, 60 * 1000, 60 * 1000);

The thing is that work of myTimerTask lasts some time.

I would like this behavior:

wait 60 sec.

do task for some time (e.g. 40 - 100 sec).

task finished.

wait 60 seconds.

do task for some time (e.g. 40 - 100 sec).

But the code above behaves like this

wait 60 sec.

do task for some time (e.g. 40 - 100 sec).

task finished

do task for some time (e.g. 40 - 100 sec).

Because the time duration of task is bigger than 60, timer starts task immediately after task is finished. But I would like it to wait again.

解决方案

This works. The key is to have the task itself (after it completes) schedule the next occurrence of the task.

import java.util.Timer;

import java.util.TimerTask;

public class TaskManager {

private Timer timer = new Timer();

public static void main(String[] args) {

TaskManager manager = new TaskManager();

manager.startTask();

}

public void startTask() {

timer.schedule(new PeriodicTask(), 0);

}

private class PeriodicTask extends TimerTask {

@Override

public void run() {

System.out.println(System.currentTimeMillis() + " Running");

/* replace with the actual task */

try {

Thread.sleep(15 * 1000);

} catch(InterruptedException e) {

e.printStackTrace();

}

/* end task processing */

System.out.println(System.currentTimeMillis() + " Scheduling 10 seconds from now");

timer.schedule(new PeriodicTask(), 10 * 1000);

}

}

}

Which prints:

$ javac TaskManager.java && java TaskManager

1288282514688 Running

1288282529711 Scheduling 10 seconds from now

1288282539712 Running

1288282554713 Scheduling 10 seconds from now

1288282564714 Running

Here's what it looks like if you extract the second components of the timestamps (for clarity):

$ javac TaskManager.java && java TaskManager

14 Running

29 (+15 seconds execution) Scheduling 10 seconds from now

39 (+10 seconds delay until next run) Running

54 (+15 seconds execution) Scheduling 10 seconds from now

64 (+10 seconds delay until next run) Running

Just replace the 10s with 60s.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值