主要是想实现消息定时发送任务,但是消息超过阈值之后也会将消息发送,这个时候定时任务就需要延后执行
-
线程等待实现 (还未试过)
-
JDK自带的Timer
核心方法:// 在指定延迟时间后执行指定的任务 schedule(TimerTask task,long delay); // 在指定时间执行指定的任务。(只执行一次) schedule(TimerTask task, Date time); // 延迟指定时间(delay)之后,开始以指定的间隔(period)重复执行指定的任务 schedule(TimerTask task,long delay,long period); // 在指定的时间开始按照指定的间隔(period)重复执行指定的任务 schedule(TimerTask task, Date firstTime , long period); // 在指定的时间开始进行重复的固定速率执行任务 scheduleAtFixedRate(TimerTask task,Date firstTime,long period); // 在指定的延迟后开始进行重复的固定速率执行任务 scheduleAtFixedRate(TimerTask task,long delay,long period); // 终止此计时器,丢弃所有当前已安排的任务。 cancal(); // 从此计时器的任务队列中移除所有已取消的任务。 purge();
试过scheduleAtFixedRate,但是这个定时任务一旦开启,其延时时间就改不了了,除非重新起一个定时任务,但是,这个的定时任务使用cancal()取消之后,再次调用同一个定时任务就会报错。
-
JDK自带的ScheduleExecutorService
ScheduledExecutorService是JAVA 1.5后新增的定时任务接口,它是基于线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行。也就是说,任务是并发执行,互不影响。需要注意:只有当执行调度任务时,ScheduledExecutorService才会真正启动一个线程,其余时间ScheduledExecutorService都是出于轮询任务的状态。
主要方法:
ScheduledFuture<?> schedule(Runnable command,long delay, TimeUnit unit); <V> ScheduledFuture<V> schedule(Callable<V> callable,long delay, TimeUnit unit); ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnitunit); ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnitunit);
当前使用的是这个方法,主要是在碰到阈值需要发送消息的时候,取消当前的定时任务,然后重启一个新延迟的定时任务,其余不触发阈值的时候依旧是定时任务执行
此外,由于不能让线程并发执行,所以采用的是单线程。kotlin代码实现:
//单线程 val executor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor() //取消当前调度任务 根据新的延时调度任务 scheduleFuture?.cancel(true) scheduleFuture = executor.scheduleWithFixedDelay(this, delayTime, interval, TimeUnit.MILLISECONDS)
-
Quartz框架实现(没试过)
-
Spring Task(没试过)
-
分布式任务调度(没试过)
参考:
https://www.baeldung.com/java-timer-and-timertask
https://blog.csdn.net/wo541075754/article/details/119405514