Java - Scheduling a daily task - java

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.

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

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?

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

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

Related

spring scheduler after maintenance

we are using spring sceduler using
#Scheduled(cron = "0 15 10 15 * ?")
the problem is that some time we have maintenece and the system is down when the job is sceduled to run.
is there another sceduler we can use ? maybe a parameter that checks if there was scedualed job that didnt run during maintenence and run it when the system is up?
or a recomenation for a different scedualer to use
Thanks
M. Deinum mentioned Quartz as a possible solution. It is a very advanced scheduling product that may handle scheduling for multiple nodes insuring that the job would run only on one node. It has many other features. I haven't used it in long while so you can look up if it is something you want to use.
However, I have dealt with your particular case in a simpler way. Part of the scheduled job responsibility was upon each run to write down into a DB table the last scheduled time (the one in the past that triggered the current run), the next scheduled time and the actual last execution time. Then, after a down time when the server starts up it has to check if the next scheduled time is in the past (also the last execution time will be older then the next scheduled time). If it is so, it is your flag that the the job missed its running due to down time (or any other reason). So you can reschedule or run it now
P.S. This will not address your actual problem, but I wrote my own scheduler and published it as part of an open-source library. My scheduler allows you to set the time intervals in more human readable form such as "4h" for 4 hours or "30m" for 30 minutes and so forth. Also it can handle multiple tasks scheduling and allows you to specify the number of threads that will handle all your scheduled tasks. You can read about it here. The library is called MgntUtils and you can get it as Maven artifacts or from Github repository releases (with source code and Javadoc included). You can read an article about the library that describes some of the features here

Execute code when system time reaches a specific time [duplicate]

This question already has answers here:
run a Java program in specific time
(2 answers)
Closed 9 years ago.
How can i implement code to do something when a specific system time is reached?
The only solution i have thought of is using a timer to "tick" every few minutes or hours to check if the specific time has been reached.
Are there any other better solutions ?
Thanks.
sorry if i had not been clear, i would be implementing the code inside my Java program, it is to clear records of a log before a new day is coming and save the records.
Example: Clear the current records and save these records at 23:59.
In pure Java, there is a Timer class. This is useful if you have a program running already. Or you are running a web app that is always up.
Another alternative is to use operating system (UNIX cron) and have it start the Java program at that time. This is useful if you don't meet the conditions for Timer.
You can just make a timer with a long duration. If the trigger time will be 350 minutes from now, there's no point having a timer poll every minute to see if the time is reached. Just set your timer to 350 minutes. Once it fires, remove the timer. This is called a one-shot timer. I can't answer how to specifically do this in Java, unfortunately.
If you are using Unix-like systems have a look at cron
If you are on Windows have a look at What is the Windows version of cron?
if i understand your question correctly, for unix, you can put your code in crontab and schedule it to run at specific system time. while for windows, you can use task scheduler. this is how we do it to run specific test scripts for nightly builds.
Quartz Scheduler Framework is an enterprise class framework that can be used as a Timer.
did you try Quartz Scheduler? , it is a powerful and advance scheduler framework, to help Java developer to scheduler a job to run at a specified date and time.click here for more
I think java.util.concurrent.ScheduledExecutorService is enough.

Is there a way to specify the duration for which a task should run using Quartz library

I am looking for a way to specify the duration for a particular task to run - e.g. a particular file cleaner task may not run longer than 2 minutes. If it finishes under 2 minutes - great, but it should terminate after 2 minutes.
Does Quartz or any other library provide some effective way of doing so?
There is no such feature in quartz. You'll have to encapsulate the "timeout manager" in your job implementation.
You should detach the actual job implementation in a separate Task that is managed by the Quartz Job.
Take a look to this example: https://stackoverflow.com/a/2275596/1517816
Assume your QuartzJob is the Test class and move your business logic in the Task class.
Hope it helps

Use Thread.sleep(), Timer or platform cron job for a periodic operation in Java EE application

I have a Java EE application which downloads stock prices from the internet every fifteen minutes. From a timing accuracy perspective is is best for the application to internalise this periodic operation i.e. use Thread.sleep() in combination with a counter or set up a timer Or would it be better to expose the task via a URL and have a platform cron job hit the URL periodically (at the the required frequency of course).
What are the pros and cons of both approaches?
I've been spooked by a timer bug I saw reported against the OpenJDK implementation. The bug stated that changes in the system time affected the operation of the time related operations and methods such as sleep and timer periodicity.
Timer is not deprecated, but a better alternative now exists: SheduledExecutorService. One of what makes it better is that it uses relative time rather than absolute time for scheduling.
Using an external cron script or an internal timer is just a matter or preference, IMHO. An internal timer is easier to setup, but if you already have other crons in place, you might want to use an additional one and have this responsibility in a single place.
Definitely consider using a scheduling job that was built for the task. Try and split the task itself from any timing considerations.
As was suggested, Quartz is a good choice.
Cron is not bad, but would require more setup to integrate with your
task.
If on Java EE you can use an EJB timer.
You can roll your own with ScheduledExecutorService (not recommended)
Thread.sleep is not a recommended way to execute code periodically. It's inaccurate and usually a sign of bad design. I suggest you use the Timer class to easily schedule the execution of code periodically.

Quartz vs. ScheduledExecutorService in Java web application

For a system monitoring Java application which currently runs on the command line and uses ScheduledExecutorService, I would like to write a simple web application version, to be run in a Servlet container like Apache Tomcat or Eclipse Jetty.
I have read about Quartz as one of the popular job schedulers for web applications. Would it be better (maybe because of better servlet container integration) to port this application from ScheduledExecutorService to Quartz?
Adding another library dependency to the application is not a problem, I am interested in technical reasons against usage of ScheduledExecutorService.
It depends on what you are using it for.
Quartz is useful for programmed times e.g. every hour on the hour.
ScheduledExecutorService is useful for repeating tasks which don't have to occur at a specific time. Its simpler and possibly more efficient. If you have this working it indicates to me that you don't need Quartz.
ScheduledExecutorService operates at a lower level and you'd have to implement all scheduling monitoring/maintenance facilities yourself.
Quartz has tons of facilities such as Job Persistence, Transactions, Clustering etc.
Java's Executor solution allows you to either:
immediately run a task
start a task after an initial delay (and optionally rerun the task after subsequent delay cycles).
But Quartz empowers you with incredible flexibility on when and how often to run a task/job. For example, one schedule during the Mon-Fri work week and something else (or not at all) during the weekends. Or on the last day of the month and you don't have to figure out if a given month's last day is on the 28th, 29th, 30th, or 31st. Here's some more examples of the flexibility the cron style scheduling accommodates - http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html#examples
Using Java's library is easier but for anyone that wants a jump start into a bare-bones codebase example of Quartz working, I've put this template together for free download usage - https://github.com/javateer/quartz-example

Categories

Resources