简体   繁体   中英

Java - Scheduling a daily task

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.

您应该看看Quartz ,这是一个基于Java的作业调度系统。

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

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.

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?

正如其他人所说,Quartz是一个选择,有了它你可以做类似cron的操作,工作或触发器,这里有一个链接: http//www.ibm.com/developerworks/java/library/j-quartz /index.html

Jcrontab

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

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