Problem with a Timer (Java.util)

Hello guys,
I have a small problem with Java timer. The problem is I wanne do some task let's say after 5 seconds, so I created a timer and set its delay to 5000 milli seconds and run my program to see that the task is well performed but the program doesn't end. I tried the timer.cancel() method or tried to assign it to null.... but never works.
So how do i make the program stop gracefully after the scheduled task finishes.
My Code...
int delay = 5000;  
          timer = new Timer();
          //timer.schedule(task, delay)
          final boolean flag =true;
          timer.schedule(new TimerTask() {
               public void run() {
                    System.out.println("hello");       // the program is still waiting after executing this.... why?
          }, delay);
          // timer.cancel();     
          System.out.println("ccc"); // these two are printed gracefully before the scheduled task... that's good.
          System.out.println("ddd");So any idea on how to solve this problem... make the timer stop after executing the required task.
Thanks in advance

Have a read of the JavaDocs, someone went to great lengths to write these to save you headaches like this.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Timer.html
Have a play around with this code un-commenting the cancel, runTimerInDifferentScope and garbage collection call to see how it behaves each time.
import java.util.Timer;
import java.util.TimerTask;
public class TimerExample {
     public static void main(String[] args) {
          final Timer timer = new Timer();
          timer.schedule(new TimerTask() {
               @Override
               public void run() {
                    System.out.println("[A] After 1 second!");
                    //timer.cancel();
          }, 1000);
          System.out.println("[A]");
          //runTimerInDifferentScope();
          //System.gc();
     private static void runTimerInDifferentScope() {
          final Timer timer = new Timer();
          timer.schedule(new TimerTask() {
               @Override
               public void run() {
                    System.out.println(" After 1 second!");
                    //No need to cancel me, I will be garbage collected
          }, 1000);
          System.out.println("[B]");
Forgot to mention that the call to System.gc() was necessary to clear the timer. This is not something you should depend on (the garbage collector) in your application. I used it in this example because it's likely it would never run with such a small program and plenty of heap space left. If in doubt then use timer.cancel() as with the first example.
Edited by: michael- on Dec 15, 2009 12:42 PM

Similar Messages

  • Getting problem with the new java.util.concurrent package

    i m using the new concurrency package of jdk 1.5 in my code. see the line:
    Executor threadPool = Executors.newCachedThreadPool();
    about this, api doc says Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available
    but i dont find this method to create new threads whenever required. please tell me about this.
    in my code, in some rare cases many threads r created, and very difficult to detect the number of active threads.
    as the previous one failed i tried with another one newFixedThreadPool(int). but here i got another problem. it works successfully but i dont understand what should be the size of the pool. i tried with 1000, it works well, but in a very rare case, it failed also. then i tried with 10000. but i m still confused, i dont know whether it would work always or not. with traditional threads my code never fails.
    please tell me, what should be the size of the pool and also let me know what is the problem with the first one (newCachedThreadPool)

    The thread pool should not be more than 100 threads. Ideally you should only have a small number of threads per CPU. If your threads are not long running it is possible that you could add 10,000 runnables but on start a small number of threads. Note, adding a thread take a non trivial amount of time so while the thread is added, all the others could finish. This could mean the number of threads could be 140 or smaller.
    Have you looked at the code to see what it does?

  • HT201250 Unexpected problem with Mac time machine!

    Hi every one!
    I'm having an unexpected problem with my time machine! the moment I hook up the back up drive my Mac crashes and the only thing I can do is to force restart. I'm not sure if the problem is with the back up disk or the Time Machine itself. I've successfully used the app since now and this just happens! I can neither access the disk in finder nor fix it by disk utility... would you please help me?
    PS. the disk is encrypted, I doubt that might be causing the problem?!    
    Thank you!
    chargar

    Launch the Console application by entering the first few letters of its name into a Spotlight search. Enter the name of the crashed process in the “Filter” text field. Post the messages from the time of the last crash, if any -- the text, please, not a screenshot.
    Then, still in the Console window, look under User Diagnostic Reports for crash logs related to the process. Select the most recent one and post the contents -- again, not a screenshot. For privacy’s sake, I suggest you edit out the “Anonymous UUID,” a long string of letters, numbers, and dashes in the header of the report, if it’s present (it may not be.)

  • Pages 08 fonts- problems with Arial, Times New Roman - how do I repair them?

    Pages 08 fonts- problems with Arial, Times New Roman - how do I repair them?
    Using 10.6.8 on MacBook Pro
    Mikeaaa

    I am running Snow Leopard. Transferring the same texts to TextEdit has no problems, so this is a Pages problem, I think.  Corruption of Times New Roman and Arial fonts, I suspect, but where? and what do I do about it? I just need to be pointed to a source of advice, I think.
    Thanks
    Mikeaaa

  • Face time fades out and then tries to reconnect on new ipad retina display on WiFi.  Iphone 4s has no problem with face time from exact same location and same contact.  WiFi signal strong on both devices.  What gives?

    Face time fades out and then retries to connect (new Ipad Retina Display) on WiFi. Iphone 4s has no problem with face time from same location and same contact.  What gives?

    rdallas001 wrote:
    Is the router to small?
    Not necessarily, if you are using Facetime all the data goes through your WiFi router, your cable/DSL modem, your ISP and the internet to Apple's Facetime servers and then, in reverse, down to the Facetime recipient. If your ISP connection is too slow or there is excessive traffic on the internet you can have Facetime problems.
    Most WiFi routers can handle this unless others in the house are also using WiFi at the same time. The problem may be your ISP connection or congestion on the internet, etc.

  • Problem with win2000sp3 and Java web start

    I have JRE and Java web start (1.2.0_01, build b01) which come downloading file j2re-1_4_1_01-windows-i586-i.exe from sun.
    I have win2000pro running on my PC.
    I had updated win2000 to service pack 2 and everything was fine.
    Now i decided to update to service pack 3 (in the process I also updated other components) from Microsoft and:
    1) Java applets seem to be running fine within i.e.
    2) If i try to run an application from java web start my PC freezes and I have to restart it.
    3) Staroffice 6.0, which runs on Java, seems to be fine.
    I reinstalled both sp3 and jre etc, with no result.
    Is this a known problem?
    Thanks to all.
    Maurizio

    I suspect that you have hit a known problem with Swing on Java 1.4.1 with buggy video drivers. Do you have an ATI card? They are the worst offenders. ATI released new drivers for its Radeon line today. They fix the problem.

  • Problem with a time zone in Belarus, Minsk

    All Belarus users of Mac and iPhone/iPad have a problem with a time zone in Belarus, Minsk. If you set time in AUTO, then time going down for 1 hour from actual time. That is happened after Belarus didn't went for winter time this year. In this case on all Mac's and iPhones and iPad's didn't work at all Face Time, iMessage, iChat. Apple still not reacting for this problem.

    Same issue here... That is really annoying when such a good things like iCal sync just doesn't work.
    Also, in case if you trying fix it somehow... here is a lot of issues related to this one. e.g. if the time zone settings were set in manual order; we're get an authorization issue with applications like Twitter...

  • Hey Guys, problem with Flex Time.

    Hey Guys,
    i have a problem with Flex Time. I was searching for a way to copy my 1-Tackt Timplin Beat to make 12 out of it, but there were always "wholes" between the new inserted regions. So i found Flex Time, but then when i choosed a Region, pressed the Flex Time button, nothing happend, except that the Header became a little bit bigger, as if there would been added a few more options, but there came only more free space .
    Would be great if somebody could help me!:)

    I would suggest Option dragging the bottom right edge of the Region so it fits precicely to the grid, then copy.  This is a quick way to time stretch...

  • Problem with summer time

    It seems that Nokia Communication Centre has a problem with summer time.
    This is the behaviour:
    - the problem
    . both on the phone and on the pc, time zone is CET+1 and summer time is active
    . on the phone I have a message received at 10
    . in the Communication Centre the time of the message is 11
    - test 1
    . on the phone, time zone is CET+1 and summer time is active
    . on the pc, time zone is CET+2 and summer time is NOT active
    . on the phone I have a message received at 10
    . in the Communication Centre the time of the message is 10
    - test 2
    . on the phone, time zone is CET+1 and summer time is active
    . on the pc, time zone is CET+1 and summer time is NOT active
    . on the phone I have a message received at 10
    . in the Communication Centre the time of the message is 9
    I'm using:
    . Windows XP Pro, italian, SP2
    . PC Suite 7.0.7.0, italian
    . Nokia 7310 Supernova, italian language, V 08.20

    george_12358 wrote:
    > What can I do to fix it?
    http://www.adobe.com/go/d2ab4470

  • I have a problem with face time

    I have a problem with face time as the mobile is sending messages to a no in UK which is 00447786205094 and this charges me a lot and I notice that it is sending this message to activate face time

    That's what happens when you buy an iPhone intended for a different market. If you want to avoid this, sell it and buy a phone intended for your market.

  • Old problem with precision time counting and /usepmtimer solution.

    Hello, all!
    There was a problem in Windows XP and 2003 Server with using QueryPerformanceCouner() function. Sometimes it can cause problem with precision time measurements on CPUs which support powersaving modes by changing clock frequency. The simplest solution for that was /usepmtimer key in boot.ini file which forces the system to use another timer.
    I just want to know does this problem appear in Windoes 7? And how to solve it since there is no boot.ini file in Windows 7?
    Thanks a lot!
    P.S. This is a page with detailed description of the problem:
    http://support.microsoft.com/default.aspx/kb/895980

    Hi ,
    There is official documentation released on userpmtimer for windows 7 operating system.
    Also the KB article only refere to the OS which have performance problem.
    After reading the below article , i feel that this problem is taken care in windows 7 / windows 2008 ( though there is no formal written documentation )
    http://blogs.technet.com/perfguru/archive/2008/02/18/explanation-for-the-usepmtimer-switch-in-the-boot-ini.aspx
    you can post in windows 7 dedicated forum, so that MVP / Microsoft Engineers and community members would suggest you with latest data if any.
    http://social.technet.microsoft.com/Forums/en-US/category/w7itpro

  • My Time Machine says there is no backup disk available.  I've never had any problems with my time machine.  I'm not technologically savvy, so if anyone can help, I'd appreciate it!

    My Time Machine says there is no backup disk available.  I've never had any problems with my time machine completing backups.  I was away from house with my laptop for about 9 days so I'm wondering if there is something I need to do now that I'm home to get it working again.  I'm not technologically savvy, so if anyone can help, I'd appreciate it!
    Thanks,
    Jana

    You can lose your ability to backup through TM for any number of reasons, but the most common is what happens after a update. If your drive still works, your best approach is to read this:
    http://www.chriscolotti.us/technology/how-to-fix-osx-mountain-lion-time-machine/
    The attached link contains helpful graphics, so don't worry if you're not tech savvy.

  • Problems with first time setup

    Hi to all and please be kind to this new applee.  I am vary familar with Windows but not Apple.
    I am having problems with first time setup.  Choice wifi network ZAJ34 has full connectino bars but requires a password to connect with it.  Tried to use "Connect to iTunes" and plugged in the USB cable.  Windows7 ran ok and "MyComputer\Apple iPod" shows up in Explorer.  All I get to is the screen that shows the cable pointing to the music symbol.  I am new to Applie iPod so I am totally lost.  I have the Apple iPod touch 8GB Black (4th Generation) CURRENT MODEL.
    Operating System - iPod touch User Guide (For iOS 5.1 Software) downloaded, not sure.
    Thanks
    Wayne

    I find this,
    Before restoring:
    Verify that you are using the latest version of iTunes. [How?  I am not past selecting a network.]
    Back up your device. [Do not know how, again, I am not past selecting a network.]
    Transfer and sync content to your computer. [Hooked up the USB cable and nothing happens.]
    Restoring your iOS device
    Connect your device to your computer. [Hooked up the USB cable and nothing happens.]
    Select your iPhone, iPad, or iPod touch when it appears in iTunes under Devices. Select the Summary tab, and click the Restore button. [iPod touch when it appears in iTunes under Devices, is it in Control Panel.  I looked in Device Manager and so only drivers etc.

  • Weird PPPoE problem with new Time Capsule

    OK, so this is a long and tedious saga, but I don't know what details are important and what are irrelevant.
    I had an old AirPort Extreme which was giving me problems. I could connect to the internet fine when I connected my MacBook directly to the DSL modem via the Ethernet cable, but when the same cable was plugged into my old AirPort it thought that there was no Ethernet cable connected to the WAN port. The AirPort was over five years old, so I figured that it was just past its time, and I kinda wanted a Time Capsule anyway for wireless backup, so I went to the Apple Store and bought one today.
    I just tried to set it up, and AirPort Utility is telling me, "This Apple wireless device is set up to connect to the Internet using PPPoE but no PPPoE server can be found. Make sure your Internet service provider requires that you use PPPoE, and make sure that the modem is turned on and connected to this Apple wireless device's WAN port and try again. If you still can't connect to the server, contact your service provider."
    Well, I did contact my ISP (AT&T Yahoo!), and they said that if I can connect directly via Ethernet, the problem has to be with the Time Capsule or its settings, so they can't help me. I've tried power cycling the DSL modem and Time Capsule, and I keep getting the same problem. Does anyone have a clue what might be going on? (I'll probably call AppleCare when they're open, but I thought someone here might be able to shed some light on the situation.)
    Thanks!

    I had a similar problem (to name one) and couldn't resolve it... I packed it back up and am returning it tomorrow.
    All these people have all these solutions but none of them should have to do any of it! That is the biggest problem I have with the TC. They give you a small little guide to set everything up and it doesn't deal with any of this. With networks and computers as they are right now.... you should not have to do any of this at all. You should be able to plug it in, answer a few easy to answer questions like it does ask and then it should configure itself just as any other network device I have purchased in the last 2 years. Even my PS3 I bought last week did it by itself by only asking a few questions! (Same as my macbook... so you know they can do it)
    Now.. say you do get it all set up and it works great... hope you don't have kids that like to play their XBox 360 online because guess what.... it isn't compatible with the TC wireless!!! If you want to use your PS3.... you have to buy more stuff.
    No.... do yourself a favor... go buy the D-Link DIR-655 that has a USB storage link... hook it up and be in business in 10 minutes. You can also get a 1TB WD external hard drive for $209.00 and hook it up direct to your mac and use time machine and transfer files faster than a mule walking up hill.

  • Running problem with a translet & Java

    Hi!
    I'm usign JDK 1.4 and Xalan 2.6.0.
    I'm able to compile the stylesheet filterAbsolutePathEscanearFuentes.xsl with the command line utility:
    java org.apache.xalan.xsltc.cmdline.Compile filterAbsolutePathEscanearFuentes.xsl
    However, when I try to run the XSL transformation using the generated translet, with the command line utility:
    java org.apache.xalan.xsltc.cmdline.Transform input.xml filterAbsolutePathEscanearFuentes
    the next error appear:
    Exception in thread "main" java.lang.VerifyError: (class: filterAbsolutePathEscanearFuentes, method: topLevel signature: (Lorg/apache/xalan/xsltc/DOM;Lorg/apache/xml/dtm/DTMAxisIterator;Lorg/apache/xml/serializer/SerializationHandler;)V) Bad type in putfield/putstatic
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:1610)
    at java.lang.Class.getConstructor0(Class.java:1922)
    at java.lang.Class.newInstance0(Class.java:278)
    at java.lang.Class.newInstance(Class.java:261)
    at org.apache.xalan.xsltc.cmdline.Transform.doTransform(Transform.java:100)
    at org.apache.xalan.xsltc.cmdline.Transform.main(Transform.java:297)
    Could you help me, please? I don't know what's the problem.
    Thank you so much for read this e-mail.

    It blocks because whoever is reading the other end is
    slow and all the intermediate buffers have been
    filled up. There is nothing short of NIO that you can
    do about it at the writing end. You need to
    investigate why the reader is slow.That was it! The application was running in debug mode, and my read loop sometimes logs statistic info. Which is bad when blocked. Now I have thrown out the unnecessary debug statements, and it runs smoothly. Thanks alot ejp!

Maybe you are looking for