ScheduledThreadPoolExecutor, how stop runnable class JAVA -


i have written following code:

import java.util.calendar; import java.util.concurrent.scheduledthreadpoolexecutor; import java.util.concurrent.timeunit;  class voter {    public static void main(string[] args) {     scheduledthreadpoolexecutor stpe = new scheduledthreadpoolexecutor(2);     stpe.scheduleatfixedrate(new shoot(), 0, 1, timeunit.seconds); } }  class shoot implements runnable { calendar deadline; long endtime,currenttime;  public shoot() {     deadline = calendar.getinstance();     deadline.set(2011,6,21,12,18,00);     endtime = deadline.gettime().gettime(); }  public void work() {     currenttime = system.currenttimemillis();      if (currenttime >= endtime) {         system.out.println("got it!");         func();     }  }  public void run() {     work(); }  public void func() {     // function called when time matches } } 

i stop scheduledthreadpoolexecutor when func() called. there no need work futher! think should put function func() inside voter class, , create kind of callback. maybe can within shoot class.

how can solve properly?

the scheduledthreadpoolexecutor allows execute task right away or schedule executed later (you can set periodical executions also).

so, if use class stop task execution keep in mind this:

  1. there no way guarantee 1 thread stop execution. check thread.interrupt() documentation.
  2. the method scheduledthreadpoolexecutor.shutdown() set canceled task, , not try interrupt threads. method avoid execution of newer tasks, , execution of scheduled not started tasks.
  3. the method scheduledthreadpoolexecutor.shutdownnow() interrupt threads, said in first point of list ...

when want stop scheduler must this:

    //cancel scheduled not started task, , avoid new ones     myscheduler.shutdown();      //wait running tasks      myscheduler.awaittermination(30, timeunit.seconds);      //interrupt threads , shutdown scheduler     myscheduler.shutdownnow(); 

but if need stop 1 task?

the method scheduledthreadpoolexecutor.schedule(...) returns schedulefuture representation of scheduled task. so, can call schedulefuture.cancel(boolean mayinterruptifrunning) method cancel task , try interrupt if need to.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -