Skip to content

Instantly share code, notes, and snippets.

@damondouglas
Last active February 21, 2024 23:00
Show Gist options
  • Save damondouglas/bff0ef9c56fb7f1eaa5d24d1c2931d7d to your computer and use it in GitHub Desktop.
Save damondouglas/bff0ef9c56fb7f1eaa5d24d1c2931d7d to your computer and use it in GitHub Desktop.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.ListCoder;
import org.apache.beam.sdk.coders.VarLongCoder;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.StateSpecs;
import org.apache.beam.sdk.state.TimeDomain;
import org.apache.beam.sdk.state.Timer;
import org.apache.beam.sdk.state.TimerSpec;
import org.apache.beam.sdk.state.TimerSpecs;
import org.apache.beam.sdk.state.ValueState;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.WithKeys;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.MoreObjects;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BatchProcessTimerExample {
public static void main(String[] args) {
PipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(PipelineOptions.class);
Pipeline pipeline = Pipeline.create(options);
pipeline
.apply(Create.of(Stream.iterate(0L, i -> i + 1).limit(1000).collect(Collectors.toList())))
.apply(WithKeys.of(0L))
.apply(useEventTimeAsTimer(VarLongCoder.of(), Duration.standardSeconds(1L)))
.apply(Log.of());
pipeline.run();
}
private static <T> ParDo.SingleOutput<KV<Long, T>, T> useEventTimeAsTimer(
Coder<T> coder, Duration interval) {
return ParDo.of(new UseEventTimeAsTimerFn<>(coder, interval));
}
private static class UseEventTimeAsTimerFn<T> extends DoFn<KV<Long, T>, T> {
private static final String TIMER_ID = "timerId";
private static final String QUEUE_ID = "queue";
private static final String RECORDED_TIMER_TIMESTAMP_ID = "recordedTimerTimestamp";
@TimerId(TIMER_ID)
private final TimerSpec timerSpec = TimerSpecs.timer(TimeDomain.PROCESSING_TIME);
@StateId(QUEUE_ID)
private final StateSpec<ValueState<List<T>>> queueStateSpec;
@StateId(RECORDED_TIMER_TIMESTAMP_ID)
private final StateSpec<ValueState<Long>> recordedTimerTimestampStateSpec = StateSpecs.value();
private final Duration interval;
private UseEventTimeAsTimerFn(Coder<T> coder, Duration interval) {
queueStateSpec = StateSpecs.value(ListCoder.of(coder));
this.interval = interval;
}
@ProcessElement
public void process(
@Element KV<Long, T> element,
@Timestamp Instant elementTimestamp,
@StateId(QUEUE_ID) ValueState<List<T>> queueState,
@TimerId(TIMER_ID) Timer timer,
@StateId(RECORDED_TIMER_TIMESTAMP_ID) ValueState<Long> recordedTimerTimestampState) {
List<T> queue = MoreObjects.firstNonNull(queueState.read(), new ArrayList<>());
queue.add(element.getValue());
queueState.write(queue);
if (recordedTimerTimestampState.read() == null) {
timer.offset(interval).setRelative();
recordedTimerTimestampState.write(timer.getCurrentRelativeTime().getMillis());
}
}
@OnTimer(TIMER_ID)
public void onTimer(
@TimerId(TIMER_ID) Timer timer,
@StateId(QUEUE_ID) ValueState<List<T>> queueState,
@StateId(RECORDED_TIMER_TIMESTAMP_ID) ValueState<Long> recordedTimerTimestampState,
OutputReceiver<T> receiver) {
List<T> queue = MoreObjects.firstNonNull(queueState.read(), new ArrayList<>());
if (queue.isEmpty()) {
timer.clear();
return;
}
receiver.output(queue.remove(0));
queueState.write(queue);
if (queue.isEmpty()) {
return;
}
timer.offset(interval).setRelative();
recordedTimerTimestampState.write(timer.getCurrentRelativeTime().getMillis());
}
}
private static class Log {
private static final Logger LOG = LoggerFactory.getLogger(Log.class);
private static final Instant START = Instant.now();
static <T> ParDo.SingleOutput<T, T> of() {
return ParDo.of(new Log.Fn<>());
}
private static class Fn<T> extends DoFn<T, T> {
@ProcessElement
public void process(@Element T t, OutputReceiver<T> receiver) {
Duration elapsed = Duration.millis(Instant.now().getMillis() - START.getMillis());
LOG.info("{}: {}", elapsed, t);
receiver.output(t);
}
}
}
}
@damondouglas
Copy link
Author

Running this example on both local and Dataflow runners has no output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment