Running Java scheduler depends on clock time - java

I have a particular requirement on scheduler. I need to run a scheduler after every 30 minutes. This can be done easily but the problem is this scheduler is depends on clock time. Like suppose I have start my program at 00:15 then with start my scheduler will not start. First scheduler will run at 00:30 and from then it will run with 30 minutes interval.
Need help on the same. I am using Java 8.

Timer and TimerTask classes can be used.
Timer class contains a method schedule() in that you can pass your task(TimerTask).
Sigtnature of the method as follows :
public void schedule(TimerTask task,long delay,long period)
First parameter : TimerTask object
Second paramter : delay in millisecond, after the mentioned milliseconds task will start to execute.
Third parameter: period in millicond, subsequent executions will happen at regular intervals of mentioned period of time.
Refer to : https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html

What you looking for is called cron sceduling it can give you the ability to run your job for example every Monday at 10 am or every 30 minute of every hour
here are some links
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
How to create a Java cron job
https://www.mkyong.com/java/java-cron-job-to-run-a-jar-file/

This requirement is called crn job. The below cron settings needed to achieve the above requirement.
*/30 * * * *

Related

Java Run Method every 30th second of a minute

I have the following while loop:
while (keepRunning) {
if (!once) {
// Run a test method every 30th second
// Run the new calculations from the database
new CalculatorDriver().run();
// Wait in the while loop for 1 second before looping again
TimeUnit.SECONDS.sleep(1);
}
}
This while loop will loop every second through the code, but now I want to run a method called: getNewCalculations() every 30th second of a minute, so for example, the method needs to run at:
18:26:30
18:27:30
18:28:30
I already found a way to run a method every x seconds:
Timer timer = new Timer();
timer.schedule(new Task(), 60 * 1000);
But I also need to start it at a specific point. In C# someone tried this to run a script every 30th and every 0th second: https://stackoverflow.com/a/53846390/10673107.
I could just add an if where the second can't be equal to 0, but I was wondering if there was a better way to do this.
How can I run it only in the 30th second?
Set an initial delay by calculating the number of seconds to wait until the next 30th second is due to arrive. If the current moment is :10, wait 20 seconds. If the current moment is :56, wait 34 seconds.
The Duration class may help with that, along with ZonedDateTime class.
If you read the Javadoc for Timer/TimerTask you will learn those classes were supplanted years ago by the Executors framework that arrived in Java 5.
Use a ScheduledExecutorService to schedule a task to run after an initial delay specified by you. After the initial delay, specify a repeating period of one minute.
Your task will then be repeating on the 30th second mark of every minute. Know that this scheduling is approximate. The host OS, the JVM’s internal scheduler, and garbage-collection all impact when the task actually runs. So each run may vary.
Or, if you want to protect against any politician-imposed anomalies on your region’s time-keeping, schedule only a one-time scheduled task rather than repeating task. Pass to that task a reference to the ScheduledExecutorService object. The task can then schedule its own next run after running the initial-delay calculation again.
Be sure to eventually shutdown your executor service. Otherwise its backing pool of threads may continue to run indefinitely even after your app ends, like a zombie 🧟‍♂️.
Be aware that any exception or error bubbling up to the scheduled executor service will silently halt any further scheduling.
All of these topics have been addressed many times already on Stack Overflow. Search to learn more.

How to stop/cancel a task in ScheduledExecutorService at particular time?

For example, I have a task which should be executed between 8:00-20:00 every minites every day.
so i calculate the time gap between 8:00 and the time which my app started for initialDelay, and use Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(command, initialDelay, 1, TimeUnit.MINUTE).
The question is, do I need the second timer to observe the task and cancel it when the clock comes to 20:00? or do I have to compare if the time is 20:00 at every time when the task's executed?
You probably need a real scheduler.
See Quartz https://quartz-scheduler.org
It should fit your needs
For the cron syntax : http://quartz-scheduler.org/api/2.2.0/org/quartz/CronTrigger.html
Or with a fluent API http://quartz-scheduler.org/api/2.2.0/org/quartz/TriggerBuilder.html

How the period of #Scheduled cron will be measured?

I need to describe how the #Scheduled annotation works.
There are three definition for Scheduled: fixedDelay, fixedRate and cron.
While the period of fixedDelay will be measured from the completion time of each preceding invocation, the period of fixedRate will be measured between the successive start times of each invocation.
But what about the cron period? How he will be measured?
Edit:
I know cron is not a period like the both fixed-information. I will describe my question with an example.
An example-method need 2 minutes to be finished. But with the #Scheduled-Annotation, I will let the method run every minute.
#Scheduled(fixedDelay = 1000)
public void exampleMethod(){}
fixedDelay will wait until the method is completed, and then he wait one minute. So the method will run every 3 Minutes.
#Scheduled(fixedRate = 1000)
public void exampleMethod(){}
fixedRate will wait one minute between the successive start times of each invocation. So the method will run every minute, doesn't matter if the method is completed or not.
#Scheduled(cron = "0 * * * * *")
public void exampleMethod(){}
So I set the cron to run every minute. Will the method be executed every minute or will cron wait until the method is completed?
Cron is a format that describes when a job should run. You can see a lot of good examples here
Cron is not perod, a format similar records indicate periodicity in Linux scheduler Cron.

Task scheduling with Quartz

I am using Quartz for scheduling parallel tasks, How can I get job running time in Quartz?
JobExecutionContext expose a some useful methods:
getJobRunTime: returns the time only after the job has actually completed
(you may want to use a JobListener to call it when job finished the
execution).
getFireTime: get the actual time the job started, so you can the current Date to calculate the elapsed time (you can call this method even inside the Job itself).
Note: To know "how long it WILL takes to run one job" you have to implement on your own doing some simple math to get the % of completion. Quartz itself doesn't have such a feature.

Java timer class, to fire at a fixed time everyday

I want to write a simple timer class that fires , and makes a method call at a fixed time of every day, while the application is running.
I dont want to use Quartz as I think its a overkill for this simple problem, what are the different approaches I can try for ?
Thanks in Advance
Why not use java.util.Timer and java.util.TimerTask?
The util.concurrent's ScheduledExecutorService allows you to pretty easily schedule tasks to run on a fixed delay. The signature of the schedule method is as follows:
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
You could find the difference between the current time and the time in which you wish to have it first run. Set the difference as the value for initialDelay. Set the period to 1 and the TimeUnit unit to TimeUnit.DAYS. That will cause it to run every day at that time.

Categories