[英]Call method every 30 seconds unless a row exists in table
I have the following class which checks a database table every second to check for rows. 我有以下类,每秒检查一次数据库表以检查行。 If a row exists it will set includeForceUpdate = true
如果存在行,则将设置includeForceUpdate = true
if the database table does not contain any rows, then I want sendUpdate
to get called every 30 seconds from the last time it was called. 如果数据库表不包含任何行,那么我希望sendUpdate
从上次调用后每30秒调用一次。
if at anytime a new row becomes available in the table then sendUpdate
will get called immediately and the 30 second timer starts from the time sendUpdate
got called. 如果在任何时候表中有新行可用,则sendUpdate
将立即被调用,并且30秒计时器从sendUpdate
被调用的时间开始。
The table should constantly be getting checked for new rows. 应不断检查表是否有新行。
I can't wrap my mind around doing this. 我无法绕过这样做。 Would I need to use more threads? 我需要使用更多线程吗?
In simple terms, I want the following to happen 简单来说,我希望发生以下情况
sendUpdate
should execute every 30 seconds. sendUpdate
应该每30秒执行一次。
However if at anytime there is a new row in the database then sendUpdate
should execute immediately bypassing the 30 seconds wait. 但是,如果数据库中有新行,则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;
}
}
I ended up using a stopwatch for the task 我最终使用秒表完成任务
@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.