How make a job to determine date only once from Java

亡梦爱人 提交于 2019-12-12 05:14:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!