java中有没有计时器_如何在Java中设置计时器?

所以,答案的第一部分是如何做主题所要求的,因为这是我最初的解释,一些人似乎觉得有帮助。问题已经澄清了,我把答案扩大到了这个问题上。

首先你需要创建一个计时器(我正在使用

java.util

此处为版本):

import java.util.Timer;

Timer timer = new Timer();

要运行任务,请执行以下操作:

timer.schedule(new TimerTask() {

@Override

public void run() {

// Your database code here

}

}, 2*60*1000);

// Since Java-8

timer.schedule(() -> /* your database code here */, 2*60*1000);

要在您要执行的持续时间之后重复此任务,请执行以下操作:

timer.scheduleAtFixedRate(new TimerTask() {

@Override

public void run() {

// Your database code here

}

}, 2*60*1000, 2*60*1000);

// Since Java-8

timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);

使任务超时

要具体执行已澄清问题所要求的操作(即尝试在给定时间段内执行任务),可以执行以下操作:

ExecutorService service = Executors.newSingleThreadExecutor();

try {

Runnable r = new Runnable() {

@Override

public void run() {

// Database task

}

};

Future> f = service.submit(r);

f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes

}

catch (final InterruptedException e) {

// The thread was interrupted during sleep, wait or join

}

catch (final TimeoutException e) {

// Took too long!

}

catch (final ExecutionException e) {

// An exception from within the Runnable task

}

finally {

service.shutdown();

}

一个问题是,虽然两分钟后会出现TimeoutException,

任务实际上将继续运行

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值