Flink定时器的触发时间

1. 代码

import org.apache.flink.api.java.utils.ParameterTool
import org.apache.flink.api.scala._
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.learn.function.{WordCountFlatMapFunction, WordCountProcessFunction}
import org.learn.source.SourceForTest


object StateWordCount {
    def main(args: Array[String]): Unit = {
        
        val parameters: ParameterTool = ParameterTool.fromArgs(args)
        val streamEnv = StreamExecutionEnvironment.getExecutionEnvironment
        streamEnv.getConfig.setGlobalJobParameters(parameters)
        
        streamEnv
          .addSource(new SourceForTest)
          .setParallelism(1)
          .flatMap(new WordCountFlatMapFunction)
          .keyBy(_._1)
          .process(new WordCountProcessFunction())

        streamEnv.execute()
    }
}

1.1 Source

import java.io.{BufferedReader, FileReader}
import java.util.concurrent.TimeUnit

import org.apache.commons.lang3.StringUtils
import org.apache.flink.streaming.api.functions.source.{RichSourceFunction, SourceFunction}

class SourceForTest extends RichSourceFunction[String] {
  private var isRunning: Boolean = true

  override def run(sourceContext: SourceFunction.SourceContext[String]): Unit = {
    val bufferedReader: BufferedReader = new BufferedReader(new FileReader("F:\\test.txt"))
    while (isRunning) {
      val line: String = bufferedReader.readLine();
      if (StringUtils.isNotBlank(line)) {
        sourceContext.collect(line);
      }
      TimeUnit.SECONDS.sleep(10);
    }
  }

  override def cancel(): Unit = {
    isRunning = false
  }
}

1.2 Map

import org.apache.flink.api.common.functions.RichFlatMapFunction
import org.apache.flink.util.Collector

class WordCountFlatMapFunction extends RichFlatMapFunction[String, (String, Int)] {
  override def flatMap(value: String, out: Collector[(String, Int)]): Unit = {
    val arr: Array[String] = value.split(",")
    for (item <- arr) {
      out.collect(Tuple2.apply(item, 1))
    }
  }
}

1.3 Process

import org.apache.flink.api.common.state.{MapState, MapStateDescriptor}
import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.functions.KeyedProcessFunction
import org.apache.flink.util.Collector

class WordCountProcessFunction extends KeyedProcessFunction[String, (String, Int), (String, Int)] {

  private var mapState: MapState[String, (String, Int)] = _
  private var timerState: MapState[Long, Long] = _

  override def open(parameters: Configuration): Unit = {
    var mapStateDesc = new MapStateDescriptor[String, (String, Int)]("valueStateDesc", classOf[String], classOf[(String, Int)])
    mapState = getRuntimeContext.getMapState(mapStateDesc)

    val timerStateDesc = new MapStateDescriptor[Long, Long]("timerStateDesc", classOf[Long], classOf[Long])
    timerState = getRuntimeContext.getMapState(timerStateDesc)
  }

  override def processElement(value: (String, Int), ctx: KeyedProcessFunction[String, (String, Int), (String, Int)]#Context, out: Collector[(String, Int)]): Unit = {

    var currentState: (String, Int) = mapState.get(value._1)
    if (null == currentState) {
      currentState = (value._1, 0)

      // TTL时间
      val ttlTime: Long = System.currentTimeMillis() - 30 * 1000 // 设置一个历史时间
      ctx.timerService().registerProcessingTimeTimer(ttlTime)
      timerState.put(ttlTime, ttlTime)
    }

    var newState: (String, Int) = (currentState._1, currentState._2 + value._2)
    mapState.put(value._1, newState)
  }

  override def onTimer(timestamp: Long, ctx: KeyedProcessFunction[String, (String, Int), (String, Int)]#OnTimerContext, out: Collector[(String, Int)]): Unit = {

    System.out.println("clear..." + " timestamp: " + timestamp + " currentTime: " + System.currentTimeMillis() + " timerState: ")
    val iter = timerState.keys().iterator()
    while (iter.hasNext) {
      val key = iter.next()
      System.out.println("key: " + key + " value: " + timerState.get(key))
    }

    mapState.clear()
  }
}

设置TTL时间为历史时间,看看定时器如何触发?

2. 结果

clear... timestamp: 1597194982850 currentTime: 1597195012866 timerState: 
key: 1597194982850 value: 1597194982850
clear... timestamp: 1597194992895 currentTime: 1597195022911 timerState: 
key: 1597194992895 value: 1597194992895
key: 1597194982850 value: 1597194982850
clear... timestamp: 1597195002910 currentTime: 1597195032925 timerState: 
key: 1597195002910 value: 1597195002910
key: 1597194992895 value: 1597194992895
key: 1597194982850 value: 1597194982850

从结果可见:

  1. 给 TimeService 设置 TTL 时间为历史时间,定时器也会触发
  2. 调用的 onTimer(timestamp, ctx, out) 函数中,参数 timestamp 的值是设置的历史时间,而不是当前时间,当前时间已经大于了 timestamp

3. 分析

当启动 TimeService 时,会注册 Timer,看看源码:

  • 进入org.apache.flink.streaming.runtime.tasks.SystemProcessingTimeService.java

      public ScheduledFuture<?> registerTimer(long timestamp, ProcessingTimeCallback target) {
    
          // delay the firing of the timer by 1 ms to align the semantics with watermark. A watermark
          // T says we won't see elements in the future with a timestamp smaller or equal to T.
          // With processing time, we therefore need to delay firing the timer by one ms.
          long delay = Math.max(timestamp - getCurrentProcessingTime(), 0) + 1;
    
          // we directly try to register the timer and only react to the status on exception
          // that way we save unnecessary volatile accesses for each timer
          try {
              return timerService.schedule(
                      new TriggerTask(status, task, checkpointLock, target, timestamp), delay, TimeUnit.MILLISECONDS);
          }
          catch (RejectedExecutionException e) {
              final int status = this.status.get();
              if (status == STATUS_QUIESCED) {
                  return new NeverCompleteFuture(delay);
              }
              else if (status == STATUS_SHUTDOWN) {
                  throw new IllegalStateException("Timer service is shut down");
              }
              else {
                  // something else happened, so propagate the exception
                  throw e;
              }
          }
      }
    
    1. 利用 timestamp - getCurrentProcessingTime()计算设置的 TTL 时间和当前时间的差值,然后取这个差值和 0 这两者中的较大值,然后 +1 作为定时器调度的延迟时间,正是这一步导致:即使设置的 TTL 时间是历史时间,也会作为当前时间来触发调度
    2. 新建 TriggerTask 任务,利用调度器定时调度该任务,触发 onTimer 操作。

看看 TriggerTask :

  • 进入org.apache.flink.streaming.runtime.tasks.SystemProcessingTimeService.TriggerTask.java

    private static final class TriggerTask implements Runnable {
    
        private final AtomicInteger serviceStatus;
        private final Object lock;
        private final ProcessingTimeCallback target;
        private final long timestamp;
        private final AsyncExceptionHandler exceptionHandler;
    
        private TriggerTask(
            final AtomicInteger serviceStatus,
            final AsyncExceptionHandler exceptionHandler,
            final Object lock,
            final ProcessingTimeCallback target,
            final long timestamp) {
    
            this.serviceStatus = Preconditions.checkNotNull(serviceStatus);
            this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler);
            this.lock = Preconditions.checkNotNull(lock);
            this.target = Preconditions.checkNotNull(target);
            this.timestamp = timestamp;
        }
    
        @Override
        public void run() {
            synchronized (lock) {
                try {
                    if (serviceStatus.get() == STATUS_ALIVE) {
                        target.onProcessingTime(timestamp);
                    }
                } catch (Throwable t) {
                    TimerException asyncException = new TimerException(t);
                    exceptionHandler.handleAsyncException("Caught exception while processing timer.", asyncException);
                }
            }
        }
    }
    
    1. TriggerTask 实现 Runnable 接口
    2. TriggerTask.timestamp 赋值为设置的 TTL 时间,正是这一步导致:调用 onTimer(timestamp, ctx, out) 函数时参数 timestamp 的值是设置的历史时间
    3. run() 方法中调用 onProcessingTime(timestamp) 方法,该方法内部触发 onTimer(timestamp, ctx, out)方法。

4. 结论

  1. 给 TimeService 设置 TTL 时间为历史时间,定时器也会触发。
  1. 调用的 onTimer(timestamp, ctx, out) 函数中,参数 timestamp 的值是设置的历史时间,而不是当前时间,当前时间已经大于了 timestamp,即无论何时触发,timestamp 永远是用户设置的 TTL 时间。
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,430评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,406评论 3 398
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,834评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,543评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,547评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,196评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,776评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,671评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,221评论 1 320
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,303评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,444评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,134评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,810评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,285评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,399评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,837评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,455评论 2 359