/** * Execute a long task with cancel and progress support. Task can be * <code>null</code>. In this case <code>runnable</code> will be executed * normally, but without cancel and progress support. * * @param task the task to be executed, can be <code>null</code>. * @param runnable the runnable to be executed * @param taskName the name of the task, is displayed in the status bar if * available * @param errorHandler error handler for exception retrieval during * execution * @throws NullPointerException if <code>runnable</code> * or * <code>taskName</code> is null * @throws IllegalStateException if a task is still executing at this time */ public synchronized void execute(LongTask task, final Runnable runnable, String taskName, LongTaskErrorHandler errorHandler) { if (runnable == null || taskName == null) { throw new NullPointerException(); } if (executor == null) { this.executor = new ThreadPoolExecutor(0, 1, 15, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory()); } RunningLongTask runningLongtask = new RunningLongTask(task, runnable, taskName, errorHandler); if (inBackground) { runningLongtask.future = executor.submit(runningLongtask); } else { currentTask = runningLongtask; runningLongtask.run(); } }
/** * Cancel the current task. If the task fails to cancel itself and if an * <code>interruptDelay</code> has been specified, the task will be * <b>interrupted</b> after <code>interruptDelay</code>. Using * <code>Thread.interrupt()</code> may cause hazardous behaviors and should * be avoided. Therefore any task should be cancelable. */ public synchronized void cancel() { if (inBackground) { if (executor != null) { RunningLongTask rlt = (RunningLongTask) currentTask; if (rlt != null) { boolean res = rlt.cancel(); if (interruptCancel && !res) { cancelTimer = new Timer(name + "_cancelTimer"); cancelTimer.schedule(new InterruptTimerTask(rlt), interruptDelay); } } } } else { RunningLongTask rlt = (RunningLongTask) currentTask; if (rlt != null) { boolean res = rlt.cancel(); if (interruptCancel && !res) { cancelTimer = new Timer(name + "_cancelTimer"); cancelTimer.schedule(new InterruptTimerTask(rlt), interruptDelay); } } } }