How to cancel a Timer from inside a TimerTask ?

I have a web application with this structure:
Tomcat starts a servlet and that starts a master thread to run once every 10 minutes,
that master thread in turn starts any number of individual tasks to run until completion,
the idea being a "shoot and forget" methodology.
public class MasterTask extends TimerTask {
// run once every 10 minutes
// retrieve a list of actions to do, this is from a database, could be 10 could be 100
// for each action schedule a TimerTask
// the reason for using a new Timer each time is that any of the action tasks
// may take a long time or not, i do not want an individual task to wait
// for a previous one to finish, therefore each task is put on it's own timer
// also in order to spread resources somewhat there is an incremental delay
// so the is some time between the start of each task as there can be many
Timer timeit;
int delay = 0;
for ( ActionTask doit : taskList ) {
timeit = new Timer();
timeit(doit,delay);
delay = delay+200;
public class ActionTask extends TimerTask {
// perform whatever actions need to be done inside this individual TimerTask
// at some point the individual task has completed it's work
// how do i completely remove it from this location ?
I know that inside the TimerTask i can call cancel() but that will only prevent it from running again it does not actually remove it completely, it remains in existence and therefore uses up memory. What i need to do is call the cancel() method on the Timer in order to remove both the Timer and TimerTask.
If i do not do this then the program will just keep creating new Timers until eternity.
( or basically until i run out of memory )
How do i call the Timer.cancel() method from INSIDE the TimerTask ?
( Note that both classes are seperate classes/files and not inside the same file or class. )
thanks,
Erik
Edited by: Datapunter on Jul 27, 2009 4:06 PM

Gotcha,
the Timer does get cancelled but the TimerTask runs to completion first.
Was expecting a kill() type effect but that is not what cancel() does.
Servlet started by Tomcat
package servlet;
import java.util.*;
import javax.servlet.ServletException;
public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    public void init() throws ServletException {
          Timer timeIt = new Timer();
          timeIt.schedule(new timertasks.testmaster(), 0, 10000); // every 10 seconds
}master task runs every 10 seconds indefinetly,
and every 10 seconds it starts (kicks off) 2 new tasks.
package timertasks;
import java.util.Timer;
import java.util.TimerTask;
public class testmaster extends TimerTask {
     public testmaster() {}
     // scheduled to run once every 10 seconds
     public void run() {
          int delay = 0;
          Timer timeit;
          for ( int count = 0; count < 2 ; count++ ) {
               timeit = new Timer();
               timeit.schedule(new ActionTask(timeit), delay, 2000);     // every 2 seconds
               delay = delay + 200;
}individual timertask, just comment out the timeit.cancel(); to see the difference in effect.
package timertasks;
import java.util.Timer;
import java.util.TimerTask;
public class ActionTask extends TimerTask {
     private Timer timeit;
     private int runcounter = 0;
     public ActionTask(Timer timeit) {
          this.timeit = timeit;
     // without cancel then values of runcounter should keep rising and more and more tasks should appear
     // with cancel each should run only once
     public void run() {
          System.out.println("before cancel, runcounter="+runcounter);
          timeit.cancel();
          System.out.println("after cancel, runcounter="+runcounter);
          runcounter++;
}thanks.

Similar Messages

  • How do I keep time from showin on calandar events ?

    how do I keep time from showin on calandar events ?

    I don't think there is any way to do this directly.  Generally speaking, Calendar shows the time of the event.  If you don't care about the time of the event you can just make it an all day event, and of course the time won't show.  Otherwise, I can only suggest the Year view .

  • How to estimate recovery time from rman backup

    how to estimate recovery time from rman backup?
    The database is of size 800GB.
    the approximate time to backup is 8- 10 hours.

    "Recovery time" is : RESTORE DATABASE time + RECOVER DATABASE time.
    RESTORE can be done
    a. in parallel with multiple channels if your backup was created as multiple backupsets
    b. using incremental backups
    c. whether the backups are on
    i. disk
    ii. tape
    Alternatively, if you have a Recovery Area with an Incrementally Update backup of the database, you can SWITCH DATABASE almost immediately
    RECOVER depends on
    a. how many archivelogs (in terms of size, not necessarily number) need to be applied
    -- this depends on
    i. transaction volume
    ii. the "freshness" of the backups (how recent the backups are)
    b. whether required archivelogs are available on disk (which can be the case if the database backup itself is a very recent backup and archivelogs since then haven't been deleted {whether they have been backed up or not}) OR whether they need to be restored from
    i. disk backup
    ii. tape backup

  • How to get a time from a NTP server in ActionScript 3 ?

    Dear All,
    I need your advice, how to get the time from NTP Server , I tried to do this, but I don't.
    Thanks
    Omar Mahmoud

    you must use a server-side language supported by your server.  php is a commonly supported language on most servers.
    php tutorials can be found via google or any other search engine.

  • How to find max(time) from table using group by

    how to find max(time) from table using group by
    select var max(time)
              from table
              into (var1, time1)
               where .....
                 group by var.
    it is fetching record which is top in table.
    if u can help?
    regards.

    No this will fetch the maximum time from teh table.
    select var max(time)
    from table xxxx
    into (var1, time1)
    where .....
    group by var.
    Refer this code
    TABLES SBOOK.
    DATA:  COUNT TYPE I, SUM TYPE P DECIMALS 2, AVG TYPE F.
    DATA:  CONNID LIKE SBOOK-CONNID.
    SELECT CONNID COUNT( * ) SUM( LUGGWEIGHT ) AVG( LUGGWEIGHT )
           INTO (CONNID, COUNT, SUM, AVG)
           FROM SBOOK
           WHERE
             CARRID   = 'LH '      AND
             FLDATE   = '19950228'
           GROUP BY CONNID.
      WRITE: / CONNID, COUNT, SUM, AVG.
    ENDSELECT.

  • How to cancel a report from web?

    i want to cancel some reports i have made from web.
    i have made two kinds of reports,one from web using /cgi-
    bin/rwcgi60.exe?runrep... and another from DOS command line
    using rwcli60.exe.Then i use /cgi-bin/rwcgi60.exe/showjobs?
    server=myreportserver and the web shows all the report jobs.
    i can kill report jobs from the web while clicking on the
    coloum 'job status',but i can't cancel all the jobs.that is to
    say i can cancel the jobs made from rwcgi60.exe?runrep... and
    cant cancel the jobs made from Dos because i have no privileges
    and the two kinds of reports belong to different owners.
    i can cancel them all from report queue manager using
    ADMINISTRATOR,but i must made the two kinds of report from web
    and dos and must cancel them all from web.
    anybody can help me how to solve the problem?
    another question:can i assign the report's owner to a special
    personal while using rwcgi.exe and rwcli60.exe?
    thanks in advance!

    Hi,
    The below link will be very useful for one who need idea on calling Oracle Report from Java Application,
    http://www.oracle.com/technology/products/reports/htdocs/getstart/examples/reportswebservice/index.html
    Thanks & Rgds,
    M T

  • How to cancel email notification from snapshot and simulation

    Hi,
    We've activated workflow template WS28700001 so that email notification can be triggered when task release. Meanwhile we are using snapshot and simulation at the same time. But when saving sanpshot or simulation the tasks which have status of released also trigger email nofitication. How to cancel this notification of snapshot and simulation?
    Regards.

    Hi Ravi
    I have added a Container Element(version) in workflow template WS28700001 and set a workflow start condition as follows.
    &Task.Version& = ' '
    Regards
    Yemi

  • How to change system time from Java

    Could someone tell me if there is possibility to change the system time, from within a Java program. And how to do it.

    In general, no.
    You could do it using JNI if you're running your JVM
    with sufficient system privileges.
    It seems a highly questionable thing to want to do.
    Why do you have a requirement for this?
    Sylvia.Now there's an idea (thread now has a 'watch'), I think I'll drop the the idea of being a hacker and learn how to write viruses instead - happy days ahead ...

  • How to set system time from Terminal while booted from 10.6.3 server install disk?

    I'm installing from a 10.6.3 server install disc onto a Mac Mini.  However, the battery on this Mac Mini is pretty much dead, forcing the system time back to 1/1/2001.  Through some research, this has created a problem in that I cannot move beyond the Welcome screen during setup of OS X server.  It looks like the binary has issues with the system time being older. 
    But I'm stuck in that I don't know how to adjust the system time from the Terminal Utility on the boot CD.  Can anyone help? 

    Hey, i just run in to something similar, tonight while trying to fix a computer.
    The user set the time and date on his computer to 1998 and computer locked everything including time and date in system preferences, and his user account basicly making him from administrator to guest. he could not almost any program properly that required administrator privilages.
    to fix this we used this comand in terminal " sudo date 201703162014 "    todays time and date
    20:17 03/16 2014
    we tryed everything and this fixed in 2 seconds
    ps: when you type sudo in terminal it whil give you a warning the improper use of this command is bad.... click continue.otherwhise you will not be able to execute the command.
    thanks again for this post and have a great day

  • How to cancel all jobs from printer

    We have network printer printing through a server, but some times some user tries to print the job locally instead of using the print server.In this case even if i clear all the jobs from the server the printer job sent to the printer trough tcp/ip  from the users computer remains hanging in the printer. In case the localy printed job is wrong or incompatible it hangs the HP printer with 49.4C02 error and there is no way to track down who sent the wrong job and printer At last the only option remains is to change the printers ip address which resolves the issue or if the user himself cancels the job from his computer. example printer : HP Color LaserJet 4700

    Just to elaborate on this answer, as Object Explorer Detail is not well known feature of SSMS, you may want to check this blog post
    Scripting all jobs on SQL Server 2005/2008 into one file
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog

  • How to run exe file from inside java

    I wan to run an exe file from inside java code. How can I do it?
    Thanks

    Hi Oakam
    This is very simple. Just go through the given code below
    in place of FILEANDPATHNAME just give the exe's path and name
    Note :- adding ".exe " is not necessary
    public class exep
    public static void main(String args[])
    Runtime r = Runtime.getRuntime();
    Process p = null;
    try{
    p = r.exec("FILEANDPATHNAME");
    catch(Exception e)
    Give ur feedback
    Thanx
    Ottran

  • HT204088 how to cancel automatic downloads from Newstand

    Please advise how to cancel an automatic download for Whole Living subscription downloaded to the Newsstand app on my iPad.  It is not simple.

    Hi Claudia ...
    Help here >  iTunes Store: Purchasing and managing auto-renewing subscriptions

  • How do I convert time from hours and minutes to decimal time

    I am making a spread sheet a work for payroll. I need to make a formula that converts the time from hours and minutes to decimal time. Please help

    Hi Taryn,
    I can't see much from the photo, but I assume your formula is similar to the one I've used below:
    The same formula is used in F4 and F6, and both return the same result (shown in F4).
    F4 was left on "automatic" cell format, and the column widened to accomodate the repeating decimal to the point where Numbers would begin displaying zeros.
    F6 was formatted as shown in the Cell Inspector to show only two decimal places.
    Neither of these is an "exact" decimal, as it is not possible to use a decimal fraction to "exactly" represent 1/6 (or 10/60).
    The likely reasons for yours showing a whole number of hours is a difference between your formula and the one shown in the example here, or a difference in the number of decimal places set in the cell's format.
    Regards,
    Barry
    PS: To take a screen shot:
    Place the mouse pointer at the top left corner of the area you want to nclude in the shot.
    Press shift-command-4.
    Use the mouse to drag a selection rectangle contining the part of the screen you want to include.
    Release the mouse button. (You'll hear the sound of a camera shutter 'snapping' the picture.)
    The screen shot will be saved to your desktop with the name 'screen shot' followed by the date and time.
    The image may be posted to the discussion using the same steps you used to post the photo above.
    B.

  • How to enter the time from the jdbc application

    Hello,
    I have a problem while entering time from my jdbc application.
    I was entering time with TIMESTAMP but it is also entering the date,i want to enter only the time in to database from my application.

    Conceptal problem
    I doubt any database supports a data type that only takes a time. The most common data type always takes a date component and time component.
    That means it will ALWAYS have a date component.
    The solution is for you to write code that ignores the date part. That can involve something like using a fixed date for all entries, stripping to seconds, using SimpleDateFormat to display/parse etc.
    Or don't use a database data type that is time specific. Instead just use a integer and stored seconds from midnight. Or some variation of that.

  • How multiple pages can be scanned at a time from inside the form6i/10g ?

    Hi All,
    I need to scan multiple pages from Oracle forms (6i/10g) using a scanner which is scanning multiple pages per minute. Can any one post a solution for me.
    Hafeez

    here are the two ways I use to scan images.
    1) if the image is a single TIF image then d2kwutil can upload the image into a BLOB field on the database (but it is limited to only SINGLE-page TIFs).
    2) if the image is a single or multi-page PDF, then your forms client must copy the image to a filesystem location known by the database (where the filesystem location is a directory on the database), and then the database can import the image into a BLOB field within the database.
    either solutions work pretty fast for me (<10 seconds per image)
    Chris

Maybe you are looking for

  • Unauthorized Issue in invoking REST API

    Hi, I am getting the following issue when i am calling the "GET" method of REST API:" https://secure.p03.eloqua.com/API/bulk/2.0/syncs/14" Unauthorized java.lang.RuntimeException: Failed : HTTP error code : 401   at GetContactSync.main(GetContactSync

  • Another BUG in Acrobat 9.4.5 -- Find doesn't work

    I made the mistake of updating to the latest version Acrobat 9.4.5, and discovered that the Find feature doesn't work right.  For example, I enter a word to search in the "Find" box, and click return.  In past versions, the PDF would jump to the firs

  • Help: photoshop cs4 crashes when i drag a layer under or over another layer/try to change layer orde

    help: photoshop cs4 crashes when i drag a layer under or over another layer/try to change layer order this problem orcurred suddenly after having used the programm for years. i tried to reinstall cs4 and install all available updates, but it di not h

  • I don't have access rights to me iTunes media

    "You don't have write access for your iTunes Media folder or a folder within it. Change permission (via Finder) and then choose Store > Check for available Downloads" How do i fix this??

  • Problem connect mac to internet with pc w/windows media center os

    I share a wireless DSL connection with my roommate. Everything was working fine for a long time until she bought a Sony PC with Windows Media Center OS on it. Every time she connects to the internet, she doesn't think it works very well for her. But,