所以,答案的第一部分是如何做主题所要求的,因为这是我最初的解释,一些人似乎觉得有帮助。问题已经澄清了,我把答案扩大到了这个问题上。
首先你需要创建一个计时器(我正在使用
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,
任务实际上将继续运行