优化连续执行 TimerTask 的服务运行
我需要一个应该始终运行的服务,直到它被我的活动显式停止为止,并且即使由于某些问题(START_STICKY
标志)而停止,也应该重新启动。该服务应该使用 TimerTask 持续执行某些操作(每隔几秒)。我最终得到了以下代码。
public class SomeService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
TimerTask timerTask;
final Handler handler = new Handler();
Timer timer = new Timer();
@Override
public void onCreate() {
// code to execute when the service is first created
super.onCreate();
}
@Override
public void onDestroy() {
// code to execute when the service is shutting down
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startid) {
// code to execute when the service is starting up
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//KEEP RUNNING SOME ERRANDS HERE
}
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 100L, 1700L);
}
}
无论如何,我可以优化它以连续运行吗?
I need a service that should always be running till its stopped explicitly by my activity and should start again even if it is stopped due to some issue (START_STICKY
flag). This service should continuously do something (every couple of seconds) using a TimerTask
. I ended up with the following code.
public class SomeService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
TimerTask timerTask;
final Handler handler = new Handler();
Timer timer = new Timer();
@Override
public void onCreate() {
// code to execute when the service is first created
super.onCreate();
}
@Override
public void onDestroy() {
// code to execute when the service is shutting down
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startid) {
// code to execute when the service is starting up
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//KEEP RUNNING SOME ERRANDS HERE
}
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 100L, 1700L);
}
}
Is there anyway that I can optimize this to run continuously?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每秒运行听起来相当过分,但是有什么理由不使用 AlarmManager 来触发 IntentService 呢?然后系统将负责可靠地触发您的服务。能否实现可靠的1秒重新触发,我不知道。出于马克在其他答案中提到的原因,这似乎是一个坏主意。
Running every second sounds pretty excessive, but is there a reason why you don't use the AlarmManager to trigger an IntentService? Then the system would be responsible for triggering your service reliably. Whether you can achieve reliable 1 second retriggers, I don't know. Seems like a bad idea for the reasons Mark is mentioning in the other answer.