Skip to content

Commit 8b039f5

Browse files
add OperationTimer
1 parent 6a4a3d0 commit 8b039f5

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/**
2+
* Copyright 2013 Netflix, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package rx.operators;
17+
18+
import java.util.concurrent.TimeUnit;
19+
20+
import rx.Observable.OnSubscribeFunc;
21+
import rx.Observer;
22+
import rx.Scheduler;
23+
import rx.Subscription;
24+
import rx.concurrency.Schedulers;
25+
import rx.subscriptions.Subscriptions;
26+
import rx.util.functions.Action0;
27+
28+
public final class OperationTimer {
29+
30+
public static OnSubscribeFunc<Void> timer(long interval, TimeUnit unit) {
31+
return timer(interval, unit, Schedulers.threadPoolForComputation());
32+
}
33+
34+
public static OnSubscribeFunc<Void> timer(final long delay, final TimeUnit unit, final Scheduler scheduler) {
35+
return new OnSubscribeFunc<Void>() {
36+
@Override
37+
public Subscription onSubscribe(Observer<? super Void> observer) {
38+
return new Timer(delay, unit, scheduler, observer).start();
39+
}
40+
};
41+
}
42+
43+
private static class Timer {
44+
private final long period;
45+
private final TimeUnit unit;
46+
private final Scheduler scheduler;
47+
private final Observer<? super Void> observer;
48+
49+
private Timer(long period, TimeUnit unit, Scheduler scheduler, Observer<? super Void> observer) {
50+
this.period = period;
51+
this.unit = unit;
52+
this.scheduler = scheduler;
53+
this.observer = observer;
54+
}
55+
56+
public Subscription start() {
57+
final Subscription s = scheduler.schedule(new Action0() {
58+
@Override
59+
public void call() {
60+
observer.onNext(null);
61+
observer.onCompleted();
62+
}
63+
}, period, unit);
64+
65+
return Subscriptions.create(new Action0() {
66+
@Override
67+
public void call() {
68+
s.unsubscribe();
69+
}
70+
});
71+
}
72+
}
73+
74+
}

0 commit comments

Comments
 (0)