Method should call once and only once in its lifecycle

NIVESH SENGAR picture NIVESH SENGAR · Mar 30, 2012 · Viewed 10.1k times · Source

I have a method which is actually a scheduler which runs a process in every one hour and create a log file every hour.
I want to call this method once in the application life cycle so I call it from a static block.
But I feel this is not working because the file is sometimes generated in one hour and sometimes early. I heard somewhere that static block only execute once is it not true?
If yes than what should I do?

Answer

jabal picture jabal · Mar 30, 2012

Static initializer blocks are executed only once when the classloader loads the class. The time they're executed is so bound to your application logic. To be more precise different classloaders might load your class so the static block can be executed more than one time theoretically.

For scheduling purposes try using out of the box a scheduler library, for example Quartz scheduler. ( http://quartz-scheduler.org) This might seem a bit of overhead the first time, however these libs offer advanced features that you may need eventually. Just a simple example: what if your program is stopped and restarted in an hour? Then the process might be run twice in this particular hour. Using quartz you can handle this situation as well.