} catch (InterruptedException e) {
e.printStackTrace();
}
} } }
new Thread(new MyThread()).start();
分析:纯正的java原生实现,在sleep结束后,并不能保证竞争到cpu资源,这也就导致了时间上必定>=10000的精度问题。
2.采用Handler的postDelayed(Runnable, long)方法
1)定义一个Handler类
Handler handler=new Handler();
Runnable runnable=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//要做的事情
handler.postDelayed(this, 2000);
}
};
handler.postDelayed(runnable, 2000);//每两秒执行一次runnable.
handler.removeCallbacks(runnable);
分析:嗯,看起蛮不错,实现上也简单了,和sleep想必还不会产生阻塞,注意等待和间隔的区别。
3.采用Handler与timer及TimerTask结合的方法
1) 定义定时器、定时器任务及Handler句柄
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);
}
};
2) 初始化计时器任务
task = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
timer.schedule(task, 2000, 3000);
timer.cancel();
private TimerTask mTimerTask = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//处理延时任务
}
});
}
};
分析:timer.schedule(task, 2000, 3000);意思是在2秒后执行第一次,之后每3000秒在执行一次。timer不保证精确度且在无法唤醒cpu,不适合后台任务的定时。
采用AlarmManger实现长期精确的定时任务
AlarmManager的常用方法有三个:
• set(int type,long startTime,PendingIntent pi);//一次性
• setExact(int type, long triggerAtMillis, PendingIntent operation)//一次性的精确版
• setRepeating(int type,long startTime,long intervalTime,PendingIntent
pi);//精确重复
• setInexactRepeating(int type,long startTime,long
intervalTime,PendingIntent pi);//非精确,降低功耗
type表示闹钟类型,startTime表示闹钟第一次执行时间,long intervalTime表示间隔时间,PendingIntent表示闹钟响应动作
对以上各个参数的详细解释
闹钟的类型:
• AlarmManager.ELAPSED_REALTIME:休眠后停止,相对开机时间
• AlarmManager.ELAPSED_REALTIME_WAKEUP:休眠状态仍可唤醒cpu继续工作,相对开机时间
• AlarmManager.RTC:同1,但时间相对于绝对时间
• AlarmManager.RTC_WAKEUP:同2,但时间相对于绝对时间
• AlarmManager.POWER_OFF_WAKEUP:关机后依旧可用,相对于绝对时间
startTime:
闹钟的第一次执行时间,以毫秒为单位,一般使用当前时间。
• SystemClock.elapsedRealtime():系统开机至今所经历时间的毫秒数
• System.currentTimeMillis():1970 年 1 月 1 日 0 点至今所经历时间的毫秒数
**intervalTime:**执行时间间隔。
PendingIntent :
PendingIntent用于描述Intent及其最终的行为.,这里用于获取定时任务的执行动作。
详细参考译文:PendingIntent
利用AlarmManger+Service+BarocastReceiver实现5s一次打印操作
服务类:
public class HorizonService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
Log.d(“TAG”, "打印时间: " + new Date().
toString());
}
}).start();
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
int five = 5000; // 这是5s
long triggerAtTime = SystemClock.elapsedRealtime() + five;
Intent i = new Intent(this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
return super.onStartCommand(intent, flags, startId);
}
}
广播接受器
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, HorizonService.class);
context.startService(i);
}
}
Intent intent = new Intent(this,HorizonService.class);
startService(intent);
效果Demo:
本例通过广播接收器和服务的循环调用实现了无限循环的效果,当然,你也可以直接利用setRepeating实现同样的效果。
注意:不要忘了在manifest文件中注册服务和广播接收器。
AlarmManager的取消方法:AlarmManger.cancel();
分析:该方式可唤醒cpu甚至实现精确定时,适用于配合service在后台执行一些长期的定时行为。
本文总结:不建议使用第一种方式,短期的定时任务推荐第二、三种方式实现,长期或者有精确要求的定时任务则可以配合Service在后台执行。
有其他疑问可下方提出或者直接链接官方文档AlarmService
前言
–
项目中总是会因为各种需求添加各种定时任务,所以就打算小结一下Android中如何实现定时任务,下面的解决方案的案例大部分都已在实际项目中实践,特此列出供需要的朋友参考,如果有什么使用不当或者存在什么问题,欢迎留言指出!直接上干货!
解决方案
普通线程sleep的方式实现定时任务
创建一个thread,然后让它在while循环里一直运行着,通过sleep方法来达到定时任务的效果,这是最常见的,可以快速简单地实现。但是这是java中的实现方式,不建议使用
public class ThreadTask {
public static void main(String[] args) {
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
public void run() {
while (true) {
System.out.println(“execute task”);
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
Timer实现定时任务
和普通线程+sleep(long)+Handler的方式比,优势在于
• 可以控制TimerTask的启动和取消
• 第一次执行任务时可以指定delay的时间。
在实现时,Timer类调度任务,TimerTask则是通过在run()方法里实现具体任务(然后通过Handler与线程协同工作,接收线程的消息来更新主UI线程的内容)。
• Timer实例可以调度多任务,它是线程安全的。当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务。
/**
• start Timer
*/
protected synchronized void startPlayerTimer() {
stopPlayerTimer();
if (playTimer == null) {
playTimer = new PlayerTimer();
Timer m_musictask = new Timer();
m_musictask.schedule(playTimer, 5000, 5000);
}
}
/**
• stop Timer
*/
protected synchronized void stopPlayerTimer() {
try {
if (playTimer != null) {
playTimer.cancel();
playTimer = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class PlayerTimer extends TimerTask {
public PlayerTimer() {
}
public void run() {
//execute task
}
}
然而Timer是存在一些缺陷的
• Timer在执行定时任务时只会创建一个线程,所以如果存在多个任务,且任务时间过长,超过了两个任务的间隔时间,会发生一些缺陷
• 如果Timer调度的某个TimerTask抛出异常,Timer会停止所有任务的运行
• Timer执行周期任务时依赖系统时间,修改系统时间容易导致任务被挂起(如果当前时间小于执行时间)
注意:
• Android中的Timer和java中的Timer还是有区别的,但是大体调用方式差不多
• Android中需要根据页面的生命周期和显隐来控制Timer的启动和取消
java中Timer:
![这里写图片描述]()
Android中的Timer:
![这里写图片描述]()
ScheduledExecutorService实现定时任务
ScheduledExecutorService是从JDK1.5做为并发工具类被引进的,存在于java.util.concurrent,这是最理想的定时任务实现方式。
相比于上面两个方法,它有以下好处:
• 相比于Timer的单线程,它是通过线程池的方式来执行任务的,所以可以支持多个任务并发执行 ,而且弥补了上面所说的Timer的缺陷
• 可以很灵活的去设定第一次执行任务delay时间
• 提供了良好的约定,以便设定执行的时间间隔
简例:
public class ScheduledExecutorServiceTask
{
public static void main(String[] args)
{
final TimerTask task = new TimerTask()
{
@Override
public void run()
{
//execute task
}
};
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
pool.scheduleAtFixedRate(task, 0 , 1000, TimeUnit.MILLISECONDS);
}
}
实际案例背景:
• 应用中多个页面涉及比赛信息展示(包括比赛状态,比赛结果),因此需要实时更新这些数据
思路分析:
• 多页面多接口刷新
*   就是每个需要刷新的页面基于自身需求基于特定接口定时刷新
*   每个页面要维护一个定时器,然后基于页面的生命周期和显隐进行定时器的开启和关闭(保证资源合理释放)
*   而且这里的刷新涉及到是刷新局部数据还是整体数据,刷新整体数据效率会比较低,显得非常笨重
• 多页面单接口刷新
*   接口给出一组需要实时进行刷新的比赛数据信息,客户端基于id进行统一过滤匹配
*   通过单例封装统一定时刷新回调接口(注意内存泄露的问题,页面销毁时关闭ScheduledExecutorService )
*   需要刷新的item统一调用,入口唯一,方便维护管理,扩展性好
*   局部刷新,效率高
public class PollingStateMachine implements INetCallback {
private static volatile PollingStateMachine instance = null;
private ScheduledExecutorService pool;
public static final int TYPE_MATCH = 1;
private Map matchMap = new HashMap<>();
private List<WeakReference> list = new ArrayList<>();
private Handler handler;
// private constructor suppresses
private PollingStateMachine() {
defineHandler();
pool = Executors.newSingleThreadScheduledExecutor();
pool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
doTasks();
}
}, 0, 10, TimeUnit.SECONDS);
}
private void doTasks() {
ThreadPoolUtils.execute(new PollRunnable(this));
}
public static PollingStateMachine getInstance() {
// if already inited, no need to get lock everytime
if (instance == null) {
synchronized (PollingStateMachine.class) {
if (instance == null) {
instance = new PollingStateMachine();
}
}
}
return instance;
}
public void subscibeMatch(VIEW view, OnViewRefreshStatus onViewRefreshStatus) {
subscibe(TYPE_MATCH,view,onViewRefreshStatus);
}
private void subscibe(int type, VIEW view, OnViewRefreshStatus onViewRefreshStatus) {
view.setTag(onViewRefreshStatus);
if (type == TYPE_MATCH) {
onViewRefreshStatus.update(view, matchMap);
}
for (WeakReference viewSoftReference : list) {
View textView = viewSoftReference.get();
if (textView == view) {
return;
}
}
WeakReference viewSoftReference = new WeakReference(view);
list.add(viewSoftReference);
}
public void updateView(final int type) {
Iterator<WeakReference> iterator = list.iterator();
while (iterator.hasNext()) {
WeakReference next = iterator.next();
final View view = next.get();
if (view == null) {
iterator.remove();
continue;
}
Object tag = view.getTag();
if (tag == null || !(tag instanceof OnViewRefreshStatus)) {
continue;
}
final OnViewRefreshStatus onViewRefreshStatus = (OnViewRefreshStatus) tag;
handler.post(new Runnable() {
@Override
public void run() {
if (type == TYPE_MATCH) {
onViewRefreshStatus.update(view, matchMap);
}
}
});
}
}
public void clear() {
pool.shutdown();
instance = null;
}
private Handler defineHandler() {
if (handler == null && Looper.myLooper() == Looper.getMainLooper()) {
handler = new Handler();
}
return handler;
}
@Override
public void onNetCallback(int type, Map msg) {
if (type == TYPE_MATCH) {
matchMap=msg;
}
updateView(type);
}
}