unscheduling a scheduled task in Android with ScheduledExecutorService -


i use scheduler ensure loop not take long, exit loop if scheduler fires , ends loop.

this quite straight forward:

public void startschedulerfortimeout() {      log.i("x", "scheduling timeout " );     timeoutforloopreached = false;     scheduler.schedule(new runnable() {     public void run() {         timeoutforloopreached = true;         log.i("x", "set timeout flag ");         }      }, 10, timeunit.seconds); } 

so in code write:

startschedulerforusbmessagetimeout(); while (!done && !timeoutforloopreached) {   ...do loop stuff } 

to make sure scheduled task not fire when run loop again need unschedule obsolete task (in case ended loop before timeout) new timer start again @ beginning of new loop (instead of old 1 firing after first loop has been finished right in between second time loop executes)

how can unschedule scheduled task has not been fired avoid scheduled task mixup?

many thanks!

use scheduledfuture:

scheduledexecutorservice scheduledtaskexecutor = executors.newscheduledthreadpool(1); runnable longrunningtask = new runnable();  // schedule long running task in 2 minutes: scheduledfuture schedulefuture = scheduledtaskexecutor.schedule(longrunningtask, 2, timeunit.minutes);  ... ... // @ point in future, if want cancel scheduled task: schedulefuture.cancel(true); ... ... 

Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -