Periodically updating the database using Java

I would like to do updates to the MySQL database using two separate classes (which do different things) - every time every 10 seconds, and the second every minute. I have a few gaps in Java knowledge, and I am wondering what is the best way to achieve this.

It is important to note that if the connection to the database is lost, I need to try reconnecting indefinitely, and I assume that using prepared statements will make the queries more efficient. Should the database connection remain open all the time or be closed between ongoing updates? Perhaps I also need to think about clearing objects / resources from memory if class instances are started indefinitely.

+4
source share
2 answers

Answer your first question "how to run a Java class in a certain interval?"

You can use quartz triggers to run a Java class on a time interval.

Second question: "what if the connection is lost?"

Check the class that runs in the time interval for connecting, if you open it, and then do not try to connect, and if it is lost, first connect to db, and then update db.

Third question: "Should the connection remain open every time?"

If you want to update with a very short period of time, then I think that yes, you should keep it open. But not sure about that. Maybe you should try to save it.

+1
source

I would keep the database connection open, but I’m not trying to manage the open connection myself. Use a pooling library, such as Apache DBCP . It allows you to specify validationQuery , which is technically a very simple SELECT query that is executed before the actual statement to check if the connection is still alive. In my application, it works solid (one application that runs 24/7, requests every minute).

0
source

Source: https://habr.com/ru/post/1334746/


All Articles