android 实现定时任务,Android 实现定时任务的五种方式的讲解

1、普通线程sleep的方式,可用于一般的轮询Polling

new Thread(new Runnable() { @Override public void run() { while (true) { //todo try { Thread.sleep(iDelay); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start();

优点:非常简单的实现,逻辑清晰明了,也是最常见的写法

缺点:在sleep结束后,并不能保证竞争到cpu资源,这也就导致了下次执行时间必定>=iDelay,存在时间精度问题

2、Timer定时器

//Timer + TimerTask结合的方法 private final Timer timer = new Timer(); private TimerTask timerTask = new TimerTask() { @Override public void run() { //todo } };

启动定时器方法:

timer.schedule(TimerTask task, long delay, long period)

立即执行

timer.schedule(timerTask, 0, 1000); //立刻执行,间隔1秒循环执行

延时执行

timer.schedule(timerTask, 2000, 1000); //等待2秒后再执行,间隔1秒循环执行

关闭定时器方法:timer.cancel();

优点:纯正的定时任务,纯java SDK,单独线程执行,比较安全,而且还可以在运行过程中取消执行

缺点:基于单线程执行,多个任务之间会相互影响,多个任务的执行是串行的,性能较低,而且timer也无法保证时间精确度,是因为手机休眠的时候,无法唤醒cpu,不适合后台任务的定时

3、ScheduledExecutorService

private Runnable runnable2 = new Runnable() { @Override public void run() { //todo } }; ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleAtFixedRate(runnable2, 0, 1, TimeUnit.SECONDS);

关于scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) 方法说明:

command:需要执行的线程

initialDelay:第一次执行需要延时的时间,如若立即执行,则initialDelay = 0

period:固定频率,周期性执行的时间

unit:时间单位,常用的有MILLISECONDS、SECONDS和MINUTES等,需要注意的是,这个单位会影响initialDelay和period,如果unit = MILLISECONDS,则initialDelay和period传入的是毫秒,如果unit = SECONDS,则initialDelay和period传入的是秒

补充一下: 还有一个方法跟上面的很相似:scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit),这个也是带延迟时间的调度,并且也是循环执行,唯一的不同就是固定延迟时间循环执行,上面的是固定频率的循环执行。那这两者的区别?

举例子:

使用scheduleAtFixedRate,任务初始延迟3秒,任务执行3秒,任务执行间隔为5秒:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); Log.e(TAG, "schedule just start! time =" + simpleDateFormat.format(System.currentTimeMillis())); executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { SystemClock.sleep(3000L); Log.e(TAG, "runnable just do it! time =" + simpleDateFormat.format(System.currentTimeMillis())); } }, 3, 5, TimeUnit.SECONDS);

执行结果截图:

f3880f905abd9c23ded45c58568aebe7.png

使用scheduleWithFixedDelay,任务初始延迟3秒,任务执行3秒,任务执行延迟为5秒:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); Log.e(TAG, "schedule just start! time =" + simpleDateFormat.format(System.currentTimeMillis())); executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { SystemClock.sleep(3000L); Log.e(TAG, "runnable just do it! time =" + simpleDateFormat.format(System.currentTimeMillis())); } }, 3, 5, TimeUnit.SECONDS);

执行结果截图:

667b1cb6d745fcc55fffb05ec26d3530.png

从这两者的运行结果就可以看到区别了:scheduleAtFixedRate是相对于任务执行的开始时间,而scheduleWithFixedDelay是相对于任务执行的结束时间。

优点:ScheduledExecutorService是一个线程池,其内部使用的延迟队列,本身就是基于等待/唤醒机制实现的,所以CPU并不会一直繁忙。解决了Timer&TimerTask存在的问题,多任务处理时效率高

缺点:取消时需要打断线程池的运行,而且和外界的通信不太好处理

4、使用Handler中的postDelayed方法

private Handler mHandler = new Handler(); private Runnable runnable = new Runnable() { @Override public void run() { //todo mHandler.postDelayed(this, iDelay); } }; mHandler.post(runnable); //立即执行 mHandler.postDelayed(runnable, iDelay); //延时执行 mHandler.removeCallbacks(runnable); //取消执行

优点:比较简单的android实现,适用UI线程

缺点:没想到,手动捂脸。。。。我估计是使用不当会造成内存泄露吧

5、Service + AlarmManger + BroadcastReceiver

本人非常推荐使用这种方式,适用于长期或者有精确要求的定时任务。我专门为这部分内容写过一篇博客,传送门:Android 定时任务之Service + AlarmManger + BroadcastReceiver

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Compose 中,可以使用 Kotlin 协程和定时器来实现定时任务。具体实现方式如下: 1. 首先,通过协程的方式执行定时任务: ```kotlin import kotlinx.coroutines.* import java.util.* fun launchTimerJob(intervalMillis: Long, action: () -> Unit): Job { return GlobalScope.launch(Dispatchers.Default) { while (isActive) { action() delay(intervalMillis) } } } ``` 该函数接受两个参数,`intervalMillis` 表示定时任务的时间间隔(毫秒),`action` 表示要执行的任务。 2. 然后,通过 `remember` 和 `LaunchedEffect` 来在 Compose 中启动和管理定时任务: ```kotlin @Composable fun TimerScreen() { val timerState = remember { TimerState() } LaunchedEffect(Unit) { timerState.timerJob = launchTimerJob(1000) { withContext(Dispatchers.Main) { timerState.updateTimer() } } } Text(text = "Timer: ${timerState.timer}") } class TimerState { var timerJob: Job? = null var timer: String by mutableStateOf("00:00:00") fun updateTimer() { val calendar = Calendar.getInstance() val hours = calendar.get(Calendar.HOUR_OF_DAY) val minutes = calendar.get(Calendar.MINUTE) val seconds = calendar.get(Calendar.SECOND) timer = String.format("%02d:%02d:%02d", hours, minutes, seconds) } } ``` 在上述代码中,`TimerScreen` 是一个 Composable 函数,用于显示定时任务的当前状态。在该函数中,通过 `remember` 创建了一个 `TimerState` 对象,用于管理定时任务的状态。然后,在 `LaunchedEffect` 中启动了定时任务,并在每次任务执行时更新了 `timer` 属性。最后,通过 `Text` 组件将 `timer` 属性的值显示出来。 需要注意的是,为了在定时任务中更新 UI,需要在 `launchTimerJob` 中使用 `Dispatchers.Main` 来切换到主线程执行任务。同时,在 `TimerState` 中使用了 `mutableStateOf` 来创建可变状态,以便在更新 UI 时自动触发 Compose 重新绘制界面。 综上所述,以上代码实现了一个简单的定时任务,可以在 Android Compose 中使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值