Java Calendar scheduling events - java

In my application i want to schedule the start of processing. In two ways first on a preset date or say like every Monday. In the case of a single date i can watch the time on a tread and start processing but when two are mixed i can't come up with a good solution.
My initial thought was when application boots up i can schedule events to calendar and check if there is job to do every min or so, that would work for both single date and every week case turns out i can not use the calendar that way.
What is a good way to solve this?

Quartz is an open-source job scheduling component written in Java, you might want to check that out.
Its features range from simple timers to full-blown CRON expressions, and it's used extensively by the JBoss AS.

Look at java.util.Timer. It allows you to schedule tasks for execution at a specified time on a background thread, and it support recurring events.

Related

Spring Boot - check if target date is reached for objects

I don't know if it's a real question or not... But i'd like to know how some of you will approach this...
I have a Spring Boot application.
Then I have a Interruttore.class, which has, among others this field timeoutDatewhich is a Date.
In the app, various instances of this class are used. The timeoutDate field can be updated, for every single object, by various factors. I need to know when the actual date reaches the timeutDate.
In a very simple (and not optimized) way i would have created a #Scheduled task, but the delay will be too short and i don't like it, how can i do?
In a very simple (and not optimized) way i would have created a
#Scheduled task, but the delay will be too short and i don't like it,
how can i do?
Why too short ?
You can use the delay you wish.
#Scheduled(fixedDelay=50000) // 50 secs
#Scheduled(fixedDelay=1000) // 1 secs
Look at the documentation for Spring's various task scheduling APIs: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
You have plenty of choices. I think the "not optimised" idea you might have is to schedule a repeating task which searches your beans to find the expired ones. That would indeed be inefficient for large numbers of beans.
You could simply create a scheduled task for each bean with a timeoutDate, created at the same time as that bean, and when its timeoutdate is updated (Spring AOP could help with this).
Alternatively you could keep a list of beans, sorted by timeout date. Schedule a task for the time of the earliest expiry. It reaps that bean and any others who's time is past, then schedules a new task for the time of the next expiry.
If you do this, you need to make sure that:
- it handles new objects added to the list (perhaps with an expiry date earlier than the currently scheduled cull)
- it handles the case where an object is removed for a reason other than a timeout
(Unless neither of those things can happen -- in which case don't worry about it!)
You can use Quartz or Jesque(redis). Whatever task needs to be executed, you can schedule that task at that time.
If this time value can be updated anytime, you can cancel(unschedule) the previously scheduled task(using task identifiers or keys) and reschedule it with the updated time.

Skipped Jobs because of DST

I have to schedule a few jobs using Java Timer using JDK1.4 without using any third-party API.
If the Daylight Saving Time (DST) change is from 2 am to 3 am , what should be the expected behavior for Jobs scheduled between the DST transition time i.e 2 am and 3 am?
Should the jobs be simply ignored as the time between 2 am and 3 am never appears on the clock
Should they be run immediately at 3 am.
Any other expected behavior ?
I think that many Enterprise applications cannot afford to skip the jobs. How should one proceed ?
Don't store/run/etc. anything using DST. It's... difficult to maintain.
UTC
Store all dates in the database in UTC. Perform all time calculations in UTC. Maintain a single standard non-changing time measurement for all business processes. Only when displaying a result to a user (showing on a screen, printing on a report, etc.) do you then localize the time to whatever that user would expect.
Basically consider all back-end logic to be in UTC, and at the interface level there would be a kind of translation layer between localized time and "system" time.
The answer by David is correct.
ScheduledExecutorService
In addition, I suggest using the ScheduledExecutorService rather than Timer.
Be sure to read up on including all the JavaDoc. Search StackOverflow to find discussion and example code. Specifically you must trap for all Exceptions or else the service will halt.

How use Task Queue to do something at a later time?

According to this Google article,
"You can also use the Task Queue to do the write at a later time, which has the added benefit that the Task Queue automatically retries failures."
Suppose I'm trying to keep my daily spend on Google App Engine under a certain budget. Let's say I start to detect I'm getting low on quota for the day so I want to reschedule the work for tomorrow. It would be great to use Task Queues for this instead of Cron jobs because the initiation of the work and the rescheduling of the work can be handled pretty similarly.
How do I put a task on the Task Queue and specify that it should not begin until a particular time? I can see how I might use RetryOptions to get part of what I want, namely to delay the work. But RetryOptions doesn't seem to provide a way to specify not to retry until 24 hours have passed since "now" or don't retry until midnight.
Thanks for your help.
Looks like I can use TaskOptions.countdownMillis(long) to specify how long to wait before executing the task.
The documentation says "later time", in the sense that your application doesn't stop to wait for your write to go through, so you work in parallel.
If you want to control WHEN to start a cleanup or something similar, look into CRON jobs

How to create a Java timer that repeats at different times

I have some stock market data. I want to simulate the stock market by having prices sent at intervals that can be determined from the times at which trades occur.
What would the best way be to do this.
So far I have a class with static variables and methods in which I am storing the hour, min, millseconds for the last trade time. I then use the trade time for the current trade and calculate it from the stored last trade values.
I then store as a static member variable the "interval" in milliseconds in the same class as the time variables are stored.
I use this line:
timer.schedule(new RemindTask(), TimeStore.getNextInterval());
where TimeStore.getNextInterval() retrieves the interval that was calculated.
Can you think of a better way, this doesnt seem to work, nor does it seem very elegant.
If you don't want to go as far as using Quartz then look at Java's ScheduledExecutorService.
http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html
Use Quartz.
From the linked page:
Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components or EJBs. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.
Well For Your Task I have a different Solution.
You can use javax.swing.Timer instead of java.util.Timer;
and then u can call the constructor by sending the delay which u want and null for action actionListeners and then you can add and addactionListeners(this) and override actionPerformed with ur task. In javax.swing.Timer the actionListeners are notified at selected interval repeatedly

Quartz job tunning

hello there is something i've realized with quartz when working.Say a cron is set to wake up every 2min with the expression 0 0/2 * * * ? .
When you run the project at say 13:10:30, the first action happens at 13:12:00 and the second 13:14:00 and every 2min 0 second for the rest. Obviously between the startup of the project and the first occurence of the action there have been 1mn:30s only.
Is there a way to for the first occurrence to respect the 2min no matter which at seconds the project starts?
Cron jobs are configured in Quartz using the CronTrigger class. The alternative is to use SimpleTrigger, which you can construct using fixed delay intervals. SimpleTrigger has various constructors, allowing you to specify the start time, end time, number of repeats, repeat interval, and so on.
Having said that, I'd recommend against using Quartz for this kind of scheduling, and use java.util.concurrent.Executors.newScheduledThreadPool(). It's much easier than Quartz when it comes to simple repeating tasks.
Quartz may use cron for the scheduling, which is based on date and time, not duration. This means that the cron expression you define is directly related to the current time on the machine, not on when the application started.
I am not aware of a Quartz configuration that will help you to solve your problem. However, a solution is to create your own Thread, which started during the launch of your application and that basically waits 2 minutes before calling a method:
while (running) {
Thread.sleep(1000 * 120);
doStuff();
}

Categories