'Create a scheduled or Cron Job that runs at a specific time of day
I need to create a scheduled job or Cron job in Java to run every morning at 6am. Is there a simple way to do it. I have tried to use Timer class with the scheduledAtFixedRate method but it takes a only a delay.
There is a method that can take a day as first time and then period
How will you create a specific date and time to start the scheduler?
My Class that needs to run the job is already extended with TimerTask.
Solution 1:[1]
When I listen something like "execute something at that precise time with Java", I am thinking about Timer or Quartz Scheduling. They have pro and cons, but you can use them safely.
You have an example of scheduled task inside that Quart Official Guide :
package org.acme.quartz;
import javax.enterprise.context.ApplicationScoped;
import javax.transaction.Transactional;
import io.quarkus.scheduler.Scheduled;
@ApplicationScoped
public class TaskBean {
@Transactional
@Scheduled(every = "10s", identity = "task-job")
void schedule() {
Task task = new Task();
task.persist();
}
}
Another way is this one, for the repeating period part :
Trigger trigger = TriggerBuilder.newTrigger().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(60).repeatForever()).build();
Another way again, is the ability to use CronExpression :
Trigger trigger = TriggerBuilder.newTrigger().startNow()
.withSchedule(CronScheduleBuilder.cronSchedule(expression))
.build();
Where expression is a CRON expression.
If you do not know Quartz, you can look at their Cookbook.
Solution 2:[2]
You can use cron4j. Or overload your method with signature (delay) with another one with signature (date,delay) that will get the current date, wait until the first occurrence and then call the already defined method with (delay) signature... aka using schedule(TimerTask task, Date firstTime, long period) of the class Timer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | dcolazin |
