如何从Java仅一次确定日期的工作 [英] How make a job to determine date only once from Java

查看:57
本文介绍了如何从Java仅一次确定日期的工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java后端。我想创建在特定日期仅运行一次的作业。
我已经在.Net中看到了示例,但我不知道在Java后端中是否可以?

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?

这是.Net作业 https://www.quartz-scheduler.net/

例如...

createJob(Date date) {
...
start(date) {
...
myMethod();

使用

createJob(myDate); //30-05-2017 15:25


推荐答案

I相信您想要的是 ScheduledExecutorService 及其
计划 接受延迟参数。可以在不同的 <$ c中指定该延迟$ c> TimeUnit 的量级为纳秒,秒,小时等。

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).

以下代码段应该为您提供一些线索(Java 8)。

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);
    }
}

您可以通过以下方式跟踪工作的完成状态 ScheduledFuture ScheduledExecutorService :: schedule 方法返回的c $ c> 对象。

You can track the completion status of your job via the ScheduledFuture object returned by the ScheduledExecutorService::schedule method.

这篇关于如何从Java仅一次确定日期的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆