JAVA代码定时避免重复,RxJava计时器可以永久重复,并且可以随时重新启动和停止...

博客围绕Android中Java代码定时任务避免重复展开。先介绍了使用Timer实现定时重复任务及停止方法,接着提到学习RxJava时遇到代码不重复的问题,最后给出解决方案,即使用interval操作符实现定时重复任务,还说明了停止任务的方法。

In android i use Timer to execute task that repeats every 5 seconds and starts after 1 second in this way:

Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {

@Override

public void run() {

// Here is the repeated task

}

}, /*Start after*/1000, /*Repeats every*/5000);

// here i stop the timer

timer.cancel();

this timer will repeat Until i call timer.cancel()

I am learning RxJava with RxAndroid extension

So i found this code on internet, i tried it and it doesnt repeat:

Observable.timer(3000, TimeUnit.MILLISECONDS)

.subscribeOn(Schedulers.newThread())

.observeOn(AndroidSchedulers.mainThread())

.subscribe(new Action1() {

@Override

public void call(Long aLong) {

// here is the task that should repeat

}

});

so what is the alternative for the android Timer in RxJava.

解决方案

timer operator emits an item after a specified delay then completes. I think you looking for the interval operator.

Subscription subscription = Observable.interval(1000, 5000, TimeUnit.MILLISECONDS)

.subscribeOn(Schedulers.io())

.observeOn(AndroidSchedulers.mainThread())

.subscribe(new Action1() {

public void call(Long aLong) {

// here is the task that should repeat

}

});

if you want to stop it you just call unsubscribe on the subscription:

subscription.unsubscribe()

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值