简体   繁体   中英

Best Way to Update Database Periodically in Java Web Application

I have a java web application which is running on Glassfish server. Using war file i use to deploy the application in various servers. Now to keep my application's database updated, i want to run some class (inside from application)periodically without any user interaction (should not depends on application is running or not/current users/session). i have seen that using some Timer and TimerTask class i can run any job periodically. But how to initialize it for the first time?

Please put your thoughts on how to complete this process.

Use a Job scheduler. Consider Quartz http://quartz-scheduler.org/ and start it when the program starts. The good part about using a scheduler is your program is more maintainable and you can easily create other new jobs

Create a servlet and make it load on startup. There you can initialize your task, I think.

Quartz is a good solution like already suggested. But if you need something more lite weight, I would have a look at the scheduled executor:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

It is less flexible than Quartz, but you don't need to add any dependency and it might be that it is good enough for your needs.

About starting up; I normally use Spring to wire up my application and its dependencies. So starting schedulers and running scheduled tasks is then a no brainer.

The answer changes depending on the version of Java EE you are using. In Java EE 5 and previous versions you would use a ServletContextListener to run code (call an EJB) at deployment time that used the Timer API . In Java EE 6+ you can use the @Schedule annotation which uses annotations and a cron-type syntax to schedule your task at deployment time.

Of course if you don't need automatic deployment time scheduling then you'd just create some web form that calls a EJB when submitted which in turn calls the Timer API programmatically.

For more see the Java EE tutorial

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM