(sorry for duplicates, if any, nntp problems...)
-cancel the tasks, not the timer.
-if you don't want to cancel 10000 tasks, write your own timer and add a
clearAllTasks() method (but avoid linkedlist, you scheduling would be too
slow)
Bonus:
-you can't cancel a running task, but with some twisted code (one more
reason to write you own), you can grab the timerthread and .interrupt()
it. Write timertasks that grabs thread.currentThread()
(the timerthread) on entry and enhance your task class with a kill()
method that simply interrupt() the timer thread BUT... be sure to catch
the interruptedexception in your task run() code: you don't want to halt
the timer thread.
public class MyTimerTask extends TimerTask {
Thread t;
final Object killtoken = "killtoken";
public void kill() {
synchronized(killtoken) {
if(t==null || t==Thread.currentThread())
throw new IllegalStateException("no thread/self-
destruct forbidden");
t.interrupt();
}
}
public void run() {
synchronized(this) {
t = Thread.currentThread();
}
try {
//code....
} catch(InterruptedException e) {
} catch(EnterruptedIOException e) {
} finally {
synchronized(this) {
t = null;
}
}
}
}
Rick Genter <> wrote in news:rgenter-
:
> I am trying to do the following:
>
> Timer timer = new Timer ();
> timer.cancel ();
>
> which is throwing an IllegalStateException. Why am I doing this? Well,
> the actual code is obviously more complex; I have a queue of tasks that
> I schedule, one at a time. I do not want to have multiple tasks
> scheduled for the timer, since there could literally be tens of
> thousands of them outstanding.
>
> The queue is maintained in ascending order of scheduled completion. The
> method that inserts an entry into the queue checks to see if it is
> inserting at the head of the queue and, if so, cancels whatever is
> currently pending and schedules the new task to fire. The problem, of
> course, occurs when inserting the first entry.
>
> According to the documentation on Timer.cancel():
>
> "Terminates this timer, discarding any currently scheduled tasks. Does
> not interfere with a currently executing task (if it exists). Once a
> timer has been terminated, its execution thread terminates gracefully,
> and no more tasks may be scheduled on it.
>
> Note that calling this method from within the run method of a timer
task
> that was invoked by this timer absolutely guarantees that the ongoing
> task execution is the last task execution that will ever be performed
by
> this timer.
>
> This method may be called repeatedly; the second and subsequent calls
> have no effect."
>
> Any ideas?
>
> Rick
> --
> Rick Genter
> <mailto:rgenter 'at' rcn 'dot' com>
>