Android中延时任务与定时任务

延时任务

新线程延迟通知主线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
mSwipeLayout.autoRefresh();
break;
}
super.handleMessage(msg);
}
};
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = new Message();
message.what = 0;
myHandler.sendMessage(message); //告诉主线程执行任务
}
}).start();

利用定时器TimerTask

1
2
3
4
5
6
7
TimerTask task = new TimerTask(){   
public void run(){
//execute the task
}
};
Timer timer = new Timer();
timer.schedule(task, delay);

Handler + postDelayed

1
2
3
4
5
new Handler().postDelayed(new Runnable(){  
public void run() {
//execute the task
}
}, delay);

Handler + Message + sendMessageAtTime

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
mSwipeLayout.autoRefresh();
break;
}
super.handleMessage(msg);
}
};

//发送消息
Message message = new Message();
message.what = 0;
myHandler.sendMessageAtTime(message, SystemClock.uptimeMillis() + 600);

Rxjava实现方式

需要的库

1
2
3
4
compile 'io.reactivex:rxjava:1.2.0'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.trello:rxlifecycle:0.4.0'
compile 'com.trello:rxlifecycle-components:0.4.0'

Activity要继承RxAppCompatActivity

调用方式

1
2
3
4
5
6
7
8
9
Observable.timer(300 , TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.compose(this.<Long>bindToLifecycle())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {

}
});

使用Kotlin协程

1
2
3
4
5
6
7
8
import kotlinx.coroutines.*

fun main() {
GlobalScope.launch {
delay(1000) // 暂停 1 秒
println("Task executed")
}
}

定时任务

定时任务的方式和上面的方式基本差不多

新线程延迟通知主线程

1
2
3
4
5
6
Handler handler = new Handler() {
public void handleMessage(Message msg) {
// 要做的事情
super.handleMessage(msg);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MyThread implements Runnable {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);// 线程暂停1秒,单位毫秒
Message message = new Message();
message.what = 1;
handler.sendMessage(message);// 发送消息
} catch (InterruptedException e) {

}
}
}
}

开始定时任务

1
2
Thread myThread = new Thread(new MyThread());
myThread.start();

取消定时任务

1
2
3
4
5
myThread.interrupt();
try {
myThread.join();
} catch (InterruptedException e) {
}

利用定时器TimerTask

1
2
3
4
5
6
7
8
9
10
private final Timer timer = new Timer();  
private TimerTask task;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
// 要做的事情
super.handleMessage(msg);
}
};

初始化

1
2
3
4
5
6
7
8
9
task = new TimerTask() {  
@Override
public void run() {
// TODO Auto-generated method stub
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};

开始定时任务

1
timer.schedule(task, 2000, 2000);

取消定时任务

1
timer.cancel();

采用Handler的postDelayed(Runnable,long)方法

1
2
3
4
5
6
7
8
Handler handler=new Handler();  
Runnable runnable=new Runnable() {
@Override
public void run() {
//要做的事情
handler.postDelayed(this, 2000);
}
};

开始定时任务

1
handler.postDelayed(runnable, 2000);//每两秒执行一次runnable.

取消定时任务

1
handler.removeCallbacks(runnable);

使用Kotlin的协程

循环执行

1
2
3
4
5
6
7
8
9
10
11
import kotlinx.coroutines.*

fun main() {
// 启动一个协程来执行无限循环的定时任务
GlobalScope.launch {
while (true) {
println("Task executed")
delay(1000) // 暂停 1 秒
}
}
}

执行多次 并监控退出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import kotlinx.coroutines.*

fun main() {
// 启动一个协程来执行定时任务
val job = GlobalScope.launch {
repeat(5) {
println("Task executed")
delay(1000) // 暂停 1 秒
}
}

// 等待协程执行完成
runBlocking {
job.join()
}

println("All tasks completed")
}

AlarmManager

利用AlarmManager,特定时刻广播指定意图,一般的简单任务不这么做

AndroidL开始repeat的周期必须大于60秒 所以短周期循环执行不建议使用