java中有没有一种方法可以根据日期/小时创建事件监听器 例如,例如每周三 15.30 运行此代码块或 11 月 15 日 17.30 运行此代码块?
最佳答案
ScheduledExecutorService
对于您的两个问题,ScheduledExecutorService
是解决方案。了解Executors framework内置于 Java 中,使多线程工作更容易、更可靠。
在特定日期/时间运行一次
this code block on 15th november at 17.30
执行器服务可以在等待一定时间后运行任务。
首先确定运行的时刻。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.of( 2020 , 11 , 15 , 17 , 30 , 0 , 0 , z );
定义要运行的任务。
Runnable runnable = new Runnable()
{
@Override
public void run ( )
{
System.out.println( "Runnable running. " + ZonedDateTime.now( z ) );
}
};
获取由线程池支持的执行器服务。
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
计算从现在到任务需要运行的时间如何等待。这里我们使用 Duration
类来计算耗时。我们传递始终采用 UTC 格式的 Instant
对象(与 UTC 的偏移量为 0 小时-分钟-秒)。
long delay = Duration.between( Instant.now() , zdt.toInstant() ).getSeconds(); // Calculate amount of time to wait until we run.
告诉执行程序服务在等待一段时间后运行任务。确保计算 delay
长整数时使用的时间单位与 TimeUnit
参数匹配。
scheduledExecutorService.schedule( runnable , delay , TimeUnit.SECONDS ); // ( Runnable , delay , TimeUnit of delay )
如果您想跟踪该任务的完成情况,请捕获 ScheduledFuture
schedule
返回的对象打电话。
重复运行
run this code block on every Wednesday at 15.30
使用与上面类似的代码。在每个任务运行结束时,计算等待下一次运行的时间,并再次调用 scheduledExecutorService.schedule
。因此,任务的一部分工作是安排其下一次运行。
如果您想按照特定时区的一天中的某个时间和一周中的某一天遵守严格的时间表,则必须遵循刚才提到的方法。政治家经常更改其管辖范围内使用的与 UTC 的偏移量,因此天数的长度会有所不同。因此,我们不能将每周任务安排为 7 天 * 24 小时 * 60 分钟 * 60 秒。周的长度各不相同,因此我们必须每次重新计算长度。
如果您确实想以完全相同的时间间隔重复运行,因此您不关心本地时钟的变化,请使用 ScheduledExecutorService.scheduleAtFixedRate
或ScheduledExecutorService.scheduleWithFixedDelay
。这些内容已在 Stack Overflow 上多次介绍,因此请搜索以了解更多信息。
关于java - 当前时间/日期事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58797904/