[英]Call method every 30 seconds unless a row exists in table
我有以下类,每秒检查一次数据库表以检查行。 如果存在行,则将设置includeForceUpdate = true
如果数据库表不包含任何行,那么我希望sendUpdate
从上次调用后每30秒调用一次。
如果在任何时候表中有新行可用,则sendUpdate
将立即被调用,并且30秒计时器从sendUpdate
被调用的时间开始。
应不断检查表是否有新行。
我无法绕过这样做。 我需要使用更多线程吗?
简单来说,我希望发生以下情况
sendUpdate
应该每30秒执行一次。
但是,如果数据库中有新行,则sendUpdate
应立即执行,绕过30秒等待。
public class Updater implements Runnable {
private volatile boolean exit = false;
Database db = new Database();
@Override
public void run() {
while (!exit) {
Boolean includeForceUpdate = false;
try {
Long id = db.getUpdate(myAccountId);
if (id != null) {
db.deleteForceUpdate(id);
sleepTime = 1;
includeForceUpdate = true;
} else {
sleepTime = 30;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void sendUpdate(Boolean includeForceUpdate) throws Exception {
//my code here for sending update
}
public void stop() {
exit = true;
}
}
我最终使用秒表完成任务
@Override
public void run() {
Database db = new Database();
Instant startTime = Instant.now();
while (!exit) {
try {
Long id = db.getUpdate(1105349L);
if (id != null) {
db.deleteUpdate(id);
}
Instant endTime = Instant.now();
Duration duration = Duration.between(startTime, endTime);
System.out.println(duration.getSeconds());
if (duration.getSeconds() >= 30 || id != null) {
System.out.println("CALLED!");
startTime = Instant.now();
}
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.