Reputation: 7841
I dont know whats wrong going on... I am not able to start a timer in my service. Following the code
public class BkgService extends Service{
private Timer ServUpdTimer = new Timer();
private static long TMR_INTERVAL = 10*60*1000;
public void onCreate() {
super.onCreate();
StartServUpdateTask();
}
private void StartServUpdateTask() {
if(ServUpdTimer != null)
ServUpdTimer.cancel();
ServUpdTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
}
}, 0, TMR_INTERVAL);
}
}
But when I reach to the line ServUpdTimer.scheduleAtFixedRate()
I am getting the following exception
03-03 23:32:14.851: E/AndroidRuntime(6083): java.lang.RuntimeException: Unable to start service mt.android.app.BkgService@40544838 with Intent { cmp=mt.android.app/.BkgService }: java.lang.IllegalStateException: Timer was canceled
I would be very grateful if someone can throw some light on this...
Upvotes: 3
Views: 3819
Reputation: 121971
From the Javadoc for Timer.cancel()
:
Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.
From the Javadoc for Timer.scheduleAtFixedRate()
:
Throws: IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
The Timer
is cancelled immediately: you need to create a new instance:
private void StartServUpdateTask() {
if(ServUpdTimer != null)
{
ServUpdTimer.cancel();
}
ServUpdTimer = new Timer();
...
}
Upvotes: 14