当前时间/日期事件监听器 [英] Current time/date event listener

查看:111
本文介绍了当前时间/日期事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java中是否有一种方法可以根据日期/小时来创建事件侦听器例如,像在每个星期三的15.30运行此代码块,还是在11月15日的17.30运行此代码块?

Is there a way in java to make an event listener based on the day/hour Like run this code block on every Wednesday at 15.30 or run this code block on 15th november at 17.30 for example?

推荐答案

ScheduledExecutorService

对于您的两个问题, ScheduledExecutorService 是解决方案.了解 执行器框架内置于Java中,使多线程工作变得更加轻松和可靠.

ScheduledExecutorService

For both your problems, ScheduledExecutorService is the solution. Learn about the Executors framework built into Java to make multi-threaded work much easier and more reliable.

此代码块在11月15日的17.30

this code block on 15th november at 17.30

执行程序服务可以在等待一定时间后运行任务.

The executor service can run a task after waiting a certain amount of time.

首先确定跑步时刻.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.of( 2020 , 11 , 15 , 17 , 30 , 0 , 0 , z );

定义您要随后运行的任务.

Define your task to be run then.

Runnable runnable = new Runnable()
{
    @Override
    public void run ( )
    {
        System.out.println( "Runnable running. " + ZonedDateTime.now( z ) );
    }
};

获得由线程池支持的执行程序服务.

Obtain an executor service, backed by a thread pool.

ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

计算从现在开始直到需要运行任务的等待时间.在这里,我们使用 Duration 类来计算经过时间.我们传递 Instant 对象,这些对象始终使用UTC(UTC偏移量为零时分-秒-秒).

Calculate how to wait from now until when the task needs to run. Here we use the Duration class to calculate elapsed time. We pass Instant objects which are always in UTC (an offset-from-UTC of zero hours-minutes-seconds).

long delay = Duration.between( Instant.now() , zdt.toInstant() ).getSeconds();  // Calculate amount of time to wait until we run.

在等待该时间后,告诉执行程序服务运行任务.确保用于计算 delay 长整数的时间单位与 TimeUnit 参数相匹配.

Tell the executor service to run the task after waiting that amount of time. Be sure that the unit-of-time used in calculating the delay long integer matches the TimeUnit argument.

scheduledExecutorService.schedule( runnable , delay , TimeUnit.SECONDS );  // ( Runnable , delay , TimeUnit of delay )

如果要跟踪该任务的完成,请捕获

If you want to track the completion of that task, capture the ScheduledFuture object returned by that schedule call.

在每个星期三的15.30运行此代码块

run this code block on every Wednesday at 15.30

使用与上面类似的代码.在每个任务运行结束时,计算等待下一次运行的时间,然后再次调用 scheduledExecutorService.schedule .因此,任务的一部分工作是安排其下一次运行.

Use code similar that that seen above. At the end of each task’s run, calculate the time to wait until the next run, and call scheduledExecutorService.schedule again. So part of the task’s work is to schedule its next run.

如果要在特定时区看到的每天和每周的某天严格遵守时间表,则必须遵循上述方法.政客通常会更改其辖区使用的UTC补偿,因此时间长度会有所不同.因此,我们不能将每周任务安排为7天* 24小时* 60分钟* 60秒.星期长短不一,因此我们必须每次都重新计算长度.

The approach just mentioned must be followed if you want to stick with a strict schedule per the time-of-day and day-of-week as seen in a particular time zone. Politicians often change the offset-from-UTC used by their jurisdictions, so the length of days vary. Therefore we cannot schedule a weekly task as being 7 days * 24 hours * 60 minutes * 60 seconds. Weeks vary in length, so we must recalculate the length each time.

如果您确实希望以完全相同的时间间隔重复运行,因此不必担心本地的时钟变化,请使用 ScheduledExecutorService.scheduleAtFixedRate

If you do want to run repeatedly with the exact same gap in time, so you do not care about the locality’s changing clock, then use ScheduledExecutorService.scheduleAtFixedRate​ or ScheduledExecutorService.scheduleWithFixedDelay​. These have been covered many times already on Stack Overflow, so search to learn more.

这篇关于当前时间/日期事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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