views:

709

answers:

6

I'm looking for an effective way to execute a method everyday at 3PM regardless of when the application was initially run or how long it has been running.

This must be done entirely from the application with no OS intervention (ex. Windows Task Scheduler)

I have been experimenting with java.util.Timer in varies configurations but I have had no success.

Any help would be appreciated.

Thanks.

+11  A: 

You should take a look at Quartz which is a Java-based job scheduling system.

Mark
Definitely use Quartz. It is my favorite scheduler. Runs as a charm
Maksim
I have always wondered. You need a running application to run Quartz in first place right? Is it possible to run it when no application has been started? How can a java application run in the background? ( maybe running within a TrayIcon or something like that? )
OscarRyz
Yes, there must be a Java application running that includes Quartz. Have a look at http://stackoverflow.com/questions/326509/java-background-daemon-service-cross-platform-best-pratices for running Java applications in the background.
Mark
+1  A: 

You can start a thread that calculates the difference to the next 3pm and sleeps for that time. When it wakes up it executes the method and recalculates and sleeps. Is this what you meant?

Norbert Hartl
+2  A: 

You will probably want to use something like the quartz engine it can do things like execute tasks that missed (like during a ahem crash) and it takes the work out of trying to manage threads.

For example if you use threads and put it to sleep and wake it up 86400 seconds (one day) later you will wake up and hour late (day = 82800 seconds) or early (day = 90000 seconds) on DST change over day, so be careful with whatever solution you choose

pfranza
+1  A: 

As stated by others Quartz is a choice, with it you can do cron-like operations, jobs or triggers, here is a link on this subject: http://www.ibm.com/developerworks/java/library/j-quartz/index.html

Alberto Zaccagni
+2  A: 

A built-in JDK way is to do what others suggested and first calculate :

  • currentTime - desiredTime

Then you can use something like a schedule executor to submit the tasks, and run them with a particular delay. This is far simpler than the options you have with frameworks like Quartz, but doesn't require an external dependency.

Also, you should always list which JDK you're using, so people can provide solutions for your version of the JDK.

Matt Reynolds
A: 

Jcrontab

Jcrontab is a scheduler written in Java. The project objective is to provide a fully functional schedules for Java projects.

Stu Thompson