开发者

How to schedule an action in java?

开发者 https://www.devze.com 2022-12-19 05:11 出处:网络
I\'m developing an application which requires Contents of the database to be written to an ms-excel file at the开发者_如何学运维 end of each day. I\'ve written the code for copying the contents into m

I'm developing an application which requires Contents of the database to be written to an ms-excel file at the开发者_如何学运维 end of each day. I've written the code for copying the contents into ms-excel file but Now how to proceed further? Whether threads are to be used to check for the completion of 24 hours or there's some other mechanism? Please provide me some guidance.


If you need to facility to run things at set times during the day, you should consider the Quartz Scheduler. It might be overkill, but it's very capable.

For example, you can use its CronTrigger to configure a job to run on a schedule defined by a cron expression, e.g. 0 23 55 * * ? (or something like that) would run your job at 5 to midnight every night (see examples).

Quartz recently got a boost to its future and fortunes by being acquired by the Terracotta folks. Hopefully it'll get some real active development now.


I agree with the others that using something like crontab would be better. However, if you can't do that, I would use the java.util.concurrent package added in Java 1.5. The class you would need is ScheduledThreadPoolExecutor. Specifically, the scheduleAtFixedRate() method.


I think that from the design perspective it is better to use crontab on linux platform or task scheduler on windows platform. It will keep your java program small, and simple. While the solution with thread waiting for the specific time seems simple it will add one serious concern - you will have to monitor its health. In addition - I would suggest to carefully plan logs your job is writing each time it is run. It is important to have logs for both successful and unsuccessful runs. It makes sense to make separate file for such logs. One more case to be considered - what to do if database was not available exactly in the time when job run? Is it acceptable to wait another 24 hours?

0

精彩评论

暂无评论...
验证码 换一张
取 消