本文的Flink源码版本为: 1.15-SNAPSHOT,读者可自行从Github clone.
Timer(定时器)是 Flink Streaming API 提供的用于感知并利用 Processing Time/Event Time 变化的机制。Ververica blog上给出的描述如下:
Timers are what make Flink streaming applications reactive and adaptable to processing and event time changes.
对于普通用户来说,最常见的显式利用 Timer 的地方就是 KeyedProcessFunction。我们在其 processElement() 方法中注册 Timer,然后覆写其 onTimer() 方法作为 Timer 触发时的回调逻辑。根据时间特征的不同:
- 处理时间——调用 Context.timerService().registerProcessingTimeTimer() 注册;onTimer() 在系统时间戳达到 Timer设定的时间戳时触发。
- 事件时间——调用 Context.timerService().registerEventTimeTimer() 注册;onTimer() 在 Flink 内部水印达到或超过 Timer 设定的时间戳时触发。
TimerService
@PublicEvolving
public interface TimerService {
String UNSUPPORTED_REGISTER_TIMER_MSG = "Setting timers is only supported on a keyed streams.&