问题
I have a Backend in Java. I want to create jobs that run only once on a certain date. I have seen examples in .Net I do not know if in my Java backend it's possible?
This is .Net jobs https://www.quartz-scheduler.net/
for example...
createJob(Date date) {
...
start(date) {
...
myMethod();
use
createJob(myDate); //30-05-2017 15:25
回答1:
I believe what you want is ScheduledExecutorService with its schedule method that accepts a delay parameter. That delay can be specified in different TimeUnit amounts such nanoseconds, seconds, hours, etc.
The idea is to calculate difference between desired date of execution and current time in some time units (seconds for example).
Here is a snippet that should give you a clue (Java 8).
public class App {
public static void main(String[] args) {
final Runnable jobToExecute = () -> System.out.println("Doing something on " + new Date());
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
ScheduledFuture future = executorService.schedule(jobToExecute, diffInSeconds(LocalDateTime.of(2017, 5, 30, 23, 54, 00)), TimeUnit.SECONDS);
}
private static long diffInSeconds(LocalDateTime dateTime) {
return dateTime.toEpochSecond(ZoneOffset.UTC) - LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
}
}
You can track the completion status of your job via the ScheduledFuture object returned by the ScheduledExecutorService::schedule
method.
来源:https://stackoverflow.com/questions/44270994/how-make-a-job-to-determine-date-only-once-from-java