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
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.
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.
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.
However if at anytime there is a new row in the database then sendUpdate
should execute immediately bypassing the 30 seconds wait.
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();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.