大数据-玩转数据-Flink定时器

一、说明

基于处理时间或者事件时间处理过一个元素之后, 注册一个定时器, 然后指定的时间执行.

Context和OnTimerContext所持有的TimerService对象拥有以下方法:

currentProcessingTime(): Long 返回当前处理时间

currentWatermark(): Long 返回当前watermark的时间戳

registerProcessingTimeTimer(timestamp: Long): Unit 会注册当前key的processing time的定时器。当processing time到达定时时间时,触发timer。

registerEventTimeTimer(timestamp: Long): Unit 会注册当前key的event time 定时器。当水位线大于等于定时器注册的时间时,触发定时器执行回调函数。

deleteProcessingTimeTimer(timestamp: Long): Unit 删除之前注册处理时间定时器。如果没有这个时间戳的定时器,则不执行。

deleteEventTimeTimer(timestamp: Long): Unit 删除之前注册的事件时间定时器,如果没有此时间戳的定时器,则不执行。

二、基于处理时间的定时器

java 复制代码
package com.lyh.flink08;

import com.lyh.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class ProcessTime {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> stream = env.socketTextStream("hadoop100", 9999)
                .map(line -> {
                    String[] datas = line.split(",");
                    return new WaterSensor(datas[0],
                            Long.valueOf(datas[1]),
                            Integer.valueOf(datas[2]));

                });
        stream.keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000);
                        out.collect(value.toString());

                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        System.out.println(timestamp);
                        out.collect("wo be chu fa le ");
                    }
                }).print();
        env.execute();
    }
}

三、基于事件时间的定时器

java 复制代码
package com.lyh.flink08;

import com.lyh.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class EventTime_s {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> stream = env.socketTextStream("hadoop100", 9999)
                .map(line -> {
                    String[] datas = line.split(",");
                    return new WaterSensor(
                            datas[0],
                            Long.valueOf(datas[1]),
                            Integer.valueOf(datas[2]));
                });

            WatermarkStrategy<WaterSensor> wms = WatermarkStrategy
            .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
            .withTimestampAssigner((element,recordTimestamp) -> element.getTs() * 1000);
            stream.assignTimestampsAndWatermarks(wms)
                    .keyBy(WaterSensor::getId)
                    .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                        @Override
                        public void processElement(WaterSensor value,
                                                   Context ctx,
                                                   Collector<String> out) throws Exception {
                            System.out.println(ctx.timestamp());
                            ctx.timerService().registerProcessingTimeTimer(ctx.timestamp()+5000);
                            out.collect(value.toString());
                        }

                        @Override
                        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                           System.out.println("定时器被触发了");
                        }
                    }).print();
            env.execute();
    }
}
相关推荐
秋刀鱼 ..9 小时前
2026生物神经网络与智能优化国际研讨会(BNNIO 2026)
大数据·python·计算机网络·数学建模·制造
AI优秘企业大脑9 小时前
增长智能体助力企业智慧转型
大数据·人工智能
正在走向自律9 小时前
时序数据库选型指南,从大数据视角看新一代列式存储引擎的核心优势
大数据·时序数据库·iotdb·国产数据库
艾莉丝努力练剑9 小时前
【Linux基础开发工具 (七)】Git 版本管理全流程与 GDB / CGDB 调试技巧
大数据·linux·运维·服务器·git·安全·elasticsearch
yuguo.im9 小时前
Elasticsearch 的倒排索引原理
大数据·elasticsearch·搜索引擎
智象科技9 小时前
从资源到业务:运维监控体系的差异
大数据·运维·一体化运维·智能运维·多云管理
IT·小灰灰10 小时前
AI成为精确的执行导演:Runway Gen-4.5如何用控制美学重塑社媒视频工业
大数据·图像处理·人工智能·python·数据分析·音视频
艾莉丝努力练剑10 小时前
【Python基础:语法第五课】Python字典高效使用指南:避开KeyError,掌握遍历与增删改查精髓
大数据·运维·人工智能·python·安全·pycharm
盛世宏博北京10 小时前
弹药库房 “感知 - 传输 - 平台 - 应用” 四层架构温湿度监控方案
java·大数据·人工智能·弹药库房温湿度监控
晓131310 小时前
SQL篇——【MySQL篇:SQL理论】索引优化、锁机制与 InnoDB
大数据