java 如何安排每小时开始的任务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10204246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:02:21  来源:igfitidea点击:

How to schedule task for start of every hour

javascheduled-tasksscheduling

提问by ImranRazaKhan

I'm developing a service that suppose to start of every hour repeating exactly on the hour (1:00PM, 2:00PM, 3:00PM, etc.).

我正在开发一项服务,该服务假设每小时开始重复整点(下午 1:00、下午 2:00、下午 3:00 等)。

I tried following but it has one problem that for first time i have to run the program exactly at start of hour and then this scheduler will repeat it.

我尝试遵循但它有一个问题,第一次我必须完全在开始时运行该程序,然后该调度程序将重复它。

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleWithFixedDelay(new MyTask(), 0, 1, TimeUnit.HOURS);

Any suggestion to repeat my task regardless when i run the program?

无论我何时运行程序,是否有任何建议可以重复我的任务?

Regards, Imran

问候, 伊姆兰

回答by krishnakumarp

I would also suggest Quartzfor this. But the above code can be made to run first at the start of the hour using the initialDelay parameter.

为此,我也建议使用Quartz。但是可以使用 initialDelay 参数使上述代码在小时开始时首先运行。

Calendar calendar = Calendar.getInstance();
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new MyTask(), millisToNextHour(calendar), 60*60*1000, TimeUnit.MILLISECONDS);



private static long millisToNextHour(Calendar calendar) {
    int minutes = calendar.get(Calendar.MINUTE);
    int seconds = calendar.get(Calendar.SECOND);
    int millis = calendar.get(Calendar.MILLISECOND);
    int minutesToNextHour = 60 - minutes;
    int secondsToNextHour = 60 - seconds;
    int millisToNextHour = 1000 - millis;
    return minutesToNextHour*60*1000 + secondsToNextHour*1000 + millisToNextHour;
}

回答by K Erlandsson

The millisToNextHourmethod in krishnakumarp's answercan be made more compact and straightforward in Java 8, which would result in the following code:

millisToNextHourkrishnakumarp 的答案中的方法可以在 Java 8 中变得更加紧凑和直接,这将导致以下代码:

public void schedule() {
    ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    scheduledExecutor.scheduleAtFixedRate(new MyTask(), millisToNextHour(), 60*60*1000, TimeUnit.MILLISECONDS);
}

private long millisToNextHour() {
    LocalDateTime nextHour = LocalDateTime.now().plusHours(1).truncatedTo(ChronoUnit.HOURS);
    return LocalDateTime.now().until(nextHour, ChronoUnit.MILLIS);
}

回答by Anonymous

If you can afford to use an external library, then Quartzprovides very flexible and easy to use scheduling modes. For example cronmode should be perfect for your case. Below a simple example of scheduling a certain Jobto be executed every hour:

如果您负担得起使用外部库,那么Quartz提供了非常灵活且易于使用的调度模式。例如cron模式应该非常适合您的情况。下面是调度某个Job每小时执行的简单示例:

quartzScheduler.scheduleJob(
    myJob, newTrigger().withIdentity("myJob", "group")
                       .withSchedule(cronSchedule("0 * * * * ?")).build());

Have a look at the tutorialand examplesto find which formulations suits your tastes. They also show how to deal with errors.

查看教程示例,找到适合您口味的配方。他们还展示了如何处理错误。

回答by deepmoteria

If you are using the spring in your service than you can directly use the annotation based scheduler @Schedule annotation which takes cron expression as a parameter or the delay in milliseconds, just add this annotation above the method you want to execute and this method will be executed. Enjoy...........

如果您在服务中使用 spring,则可以直接使用基于注释的调度程序 @Schedule 注释,该注释将 cron 表达式作为参数或以毫秒为单位的延迟,只需在要执行的方法上方添加此注释,此方法将是执行。享受...........