timer - Apache Flink - 如果 x 分钟没有收到数据,则发送事件

标签 timer apache-flink complex-event-processing data-stream

如何使用 Flink 的 DataStream API 实现一个运算符,该运算符在一段时间内未从流中接收到数据时发送事件?

最佳答案

这样的操作符可以使用 ProcessFunction 来实现。 .

DataStream<Long> input = env.fromElements(1L, 2L, 3L, 4L);

input
  // use keyBy to have keyed state. 
  // NullByteKeySelector will move all data to one task. You can also use other keys
  .keyBy(new NullByteKeySelector())
  // use process function with 60 seconds timeout
  .process(new TimeOutFunction(60 * 1000));
TimeOutFunction定义如下。在本例中,它使用处理时间。

public static class TimeOutFunction extends ProcessFunction<Long, Boolean> {

  // delay after which an alert flag is thrown
  private final long timeOut;
  // state to remember the last timer set
  private transient ValueState<Long> lastTimer;

  public TimeOutFunction(long timeOut) {
    this.timeOut = timeOut;
  }

  @Override
  public void open(Configuration conf) {
    // setup timer state
    ValueStateDescriptor<Long> lastTimerDesc = 
      new ValueStateDescriptor<Long>("lastTimer", Long.class);
    lastTimer = getRuntimeContext().getState(lastTimerDesc);
  }

  @Override
  public void processElement(Long value, Context ctx, Collector<Boolean> out) throws Exception {
    // get current time and compute timeout time
    long currentTime = ctx.timerService().currentProcessingTime();
    long timeoutTime = currentTime + timeOut;
    // register timer for timeout time
    ctx.timerService().registerProcessingTimeTimer(timeoutTime);
    // remember timeout time
    lastTimer.update(timeoutTime);
  }

  @Override
  public void onTimer(long timestamp, OnTimerContext ctx, Collector<Boolean> out) throws Exception {
    // check if this was the last timer we registered
    if (timestamp == lastTimer.value()) {
      // it was, so no data was received afterwards.
      // fire an alert.
      out.collect(true);
    }
  }
}

关于timer - Apache Flink - 如果 x 分钟没有收到数据,则发送事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059762/

相关文章:

multithreading - Perl 中的线程定时循环

java - Drools Fusion规则语言: pedometer rule

java - 创建 Esper 的 epl 实例

objective-c - 倒数日子 - iPhone倒计时

jboss - 调用计时器超时时出错 - 无法在 EJB 3 计时器服务的 5 分钟内获得锁定

在集群上运行 Flink table-api 程序时出现 java.lang.InknownClassChangeError 错误

apache-flink - 弗林克 : Difference between MaxOutOfOrderness and AllowedLateness

apache-flink - 如何统计给定时间窗口内Apache Flink处理的记录数

java - 在自定义 WSO2 组件中使用 CEP EventBuilder 服务

swift - 如何在计时器应用程序上延迟几秒?