Updating a database periodically with Java
I would like to perform updates to a MySQL database using two separate classes (that do different things) -- one doing so every 10 seconds, and the second every minute. I have a few gaps in my Java knowledge and I'm wondering what the best way to achieve it is.
Importantly, if connectivity to the database is lost, I need reconnection attempts to occur indefinitely, and I'm guessing the use of Prepared Statements will make queries more efficient. Shoul开发者_如何学Cd the connection to the database be left open all the time or closed between the updates being run? Maybe I also need to think about clearing objects/resources out of memory if the class instances are going to be run indefinitely.
Answer to your first question "how to run java class at some specific interval?"
You can use quartz triggers to run java class at time interval.
Second Question: "what if conn is lost?"
Check in class that runs at time interval for connection if its open then dont attempt to connect and if lost then first connect to db and then update the db.
Third question: "Should the connection left open every time?"
If you wanna do update with very small time gap then i think yes you should keep it open.but not sure about it. May be you should try it keeping open.
I would keep the database connection open but do noty try to manage the open connection yourself. Use a connection pooling library like Apache DBCP. It allows to specify a validationQuery which technically a very simple SELECT request that is executed before the actual statement for validating if the connection is still alive. In my application this works rock solid (one app that runs 24/7; queries about every minute).
精彩评论