{"id":1825,"date":"2011-03-24T16:23:49","date_gmt":"2011-03-24T10:53:49","guid":{"rendered":"http:\/\/JitendraZaa.com\/blog\/?p=1825"},"modified":"2011-03-24T16:23:49","modified_gmt":"2011-03-24T10:53:49","slug":"java-thread-timertask","status":"publish","type":"post","link":"https:\/\/www.jitendrazaa.com\/blog\/java\/java-thread-timertask\/","title":{"rendered":"Java Thread &#8211; Executor framework, Timer and TimerTask"},"content":{"rendered":"<p>With the Thread class you could create your own timer class using the <strong>Thread.sleep(T)<\/strong> method to delay action for some time . This approach, however, has some drawbacks. For periodic events, if the processing times in between the sleep periods vary significantly, then the overall timing will mismatch. Also, if you need many timer events, the program will require many threads and use up system resources.<\/p>\n<p>We can create a Timer functionality with<strong><a title=\"Executor Framework\" href=\"https:\/\/jitendrazaa.com\/blog\/java\/java-threading-executor-framework-and-callable-interface\/\" target=\"_blank\">Executor frameworks<\/a> <\/strong>and also there is <strong>Timer and Timertask<\/strong> available in <em>java.util package<\/em>. We will see both methods to create Timer functionality.<!--more--><\/p>\n<p><strong>Method 1<\/strong> : Using Executor framework<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.G2.Thread;\n\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.TimeUnit;\n\nclass MyTimer1 implements Runnable {\n\n\t@Override\n\tpublic void run() {\n\t\tSystem.out.println(&quot;This is run method&quot;);\n\n\t}\n\n}\n\npublic class TimerTask1Demo {\n\n\t\/**\n\t * @param args\n\t *\/\n\tpublic static void main(String&#x5B;] args) {\n\t\tMyTimer1 runnable = new MyTimer1();\n\n\t\tScheduledExecutorService thread = Executors.newSingleThreadScheduledExecutor();\n\n\t\t\/**\n\t\t * Parameters :\n\t\t * 1. Object of Runnable\n\t\t * 2. Initial Delay\n\t\t * 3. Delay between successive execution\n\t\t * 4. Time Unit\n\t\t *\/\n\t\tthread.scheduleAtFixedRate(runnable, 1000,1000, TimeUnit.MILLISECONDS);\n\n\t}\n}\n<\/pre>\n<p>After every 1 sec the o\/p will be printed.<br \/>\nTo read more on ScheduledExecutorService refer below URL: <a title=\"ScheduledExecutorService\" href=\"http:\/\/download.oracle.com\/javase\/6\/docs\/api\/java\/util\/concurrent\/ScheduledExecutorService.html\" target=\"_blank\">http:\/\/download.oracle.com\/javase\/6\/docs\/api\/java\/util\/concurrent\/ScheduledExecutorService.html<\/a><\/p>\n<p><strong>Method 2:<\/strong> Using java.util package for Progress bar animation in Swing<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.G2.Thread;\n\nimport java.util.Timer;\nimport java.util.TimerTask;\n\nimport javax.swing.JFrame;\nimport javax.swing.JProgressBar;\n\npublic class TimerTaskDemo2 {\n\tjava.util.Timer fTimer;\n\tJProgressBar prg;\n\n\tclass MyTimerTask extends TimerTask {\n\t\tpublic int progressValue = 0;\n\n\t\t@Override\n\t\tpublic void run() {\n\t\t\tprogressValue++;\n\t\t\tprg.setValue(progressValue);\n\t\t\tif (progressValue &gt; 100)\n\t\t\t\tfTimer.cancel();\n\t\t}\n\n\t}\n\n\t\/**\n\t * @param args\n\t *\/\n\tpublic static void main(String&#x5B;] args) {\n\t\tTimerTaskDemo2 obj = new TimerTaskDemo2();\n\t\tobj.createUI();\n\n\t}\n\n\tprivate void createUI() {\n\t\tJFrame f = new JFrame(&quot;Timer Task Demo&quot;);\n\t\tf.setLayout(null);\n\t\tprg = new JProgressBar();\n\t\tprg.setSize(200, 20);\n\n\t\t\/\/ Display percentage Text\n\t\tprg.setStringPainted(true);\n\t\tf.add(prg);\n\n\t\tf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tf.setSize(200, 100);\n\t\tf.setVisible(true);\n\n\t\tfTimer = new Timer();\n\t\tfTimer.schedule(new MyTimerTask(), 100, 100);\n\t}\n}\n<\/pre>\n<p>Output:<\/p>\n<figure id=\"attachment_1826\" aria-describedby=\"caption-attachment-1826\" style=\"width: 202px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2011\/03\/Animation-of-ProgressBar-Swing-Using-TimerTask.jpg?ssl=1\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-1826\" title=\"Animation of ProgressBar in Swing Using TimerTask\" src=\"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2011\/03\/Animation-of-ProgressBar-Swing-Using-TimerTask.jpg?resize=202%2C103&#038;ssl=1\" alt=\"Animation of ProgressBar in Swing Using TimerTask\" width=\"202\" height=\"103\" \/><\/a><figcaption id=\"caption-attachment-1826\" class=\"wp-caption-text\">Animation of ProgressBar in Swing Using TimerTask<\/figcaption><\/figure>\n<p>In this example we have created a class &#8220;MyTimerTask&#8221;, which extends &#8220;<strong>TimerTask<\/strong>&#8221; and then created object of &#8220;<strong>Timer<\/strong>&#8221; by passing the &#8220;MyTimerTask&#8221;\u009d and scheduled to run after every 100 msec.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Tutorial and example of  Executor framework, Timer and TimerTask over Thread<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"jz_research_post":"","_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[3],"tags":[192,198],"class_list":["post-1825","post","type-post","status-publish","format-standard","hentry","category-java","tag-swing","tag-thread"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":1820,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/java-threading-executor-framework-and-callable-interface\/","url_meta":{"origin":1825,"position":0},"title":"Java Threading &#8211; Executor Framework and Callable Interface","author":"Jitendra","date":"March 24, 2011","format":false,"excerpt":"Java Threading - Executor Framework and Callable Interface with example","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2422,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/quartz-framework-tutorial-with-example-schedule-job-in-java\/","url_meta":{"origin":1825,"position":1},"title":"Quartz framework tutorial with example &#8211; Schedule job in Java","author":"Jitendra","date":"September 22, 2011","format":false,"excerpt":"Tutorial of the Quartz framework for Java. Schedule job without loosing the performance of the application","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":999,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/bouncing-ball-applet-create-balls-on-mouse-click-of-random-color-and-random-size\/","url_meta":{"origin":1825,"position":2},"title":"Bouncing ball applet &#8211; Create Balls on Mouse click of random color and random size","author":"Jitendra","date":"September 9, 2010","format":false,"excerpt":"Creating the balls on mouse click of random color, random size and random speed and bouncing around the wall of applet in JAVA.","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"Bouncing Ball applet - Create ball on Mouse click of random size and random color","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2010\/09\/Bouncing-Ball-applet.jpg?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":1576,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/snmp\/creating-snmp-agent-server-in-java-using-snmp4j\/","url_meta":{"origin":1825,"position":3},"title":"Creating SNMP Agent (Server) in JAVA using SNMP4j","author":"Jitendra","date":"February 24, 2011","format":false,"excerpt":"Creating SNMP Agent (Server) in JAVA using SNMP4j","rel":"","context":"In &quot;SNMP&quot;","block_context":{"text":"SNMP","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/snmp\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":757,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/anonymous-classimplements-interface-methods-of-threads\/","url_meta":{"origin":1825,"position":4},"title":"Create Thread using Anonymous class and Interface","author":"Jitendra","date":"August 16, 2010","format":false,"excerpt":"Demonstration of creating Thread by Anonymous class and Interface","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":724,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/simple-threading-techniques\/","url_meta":{"origin":1825,"position":5},"title":"Thread, Life Cycle of Thread","author":"Jitendra","date":"August 7, 2010","format":false,"excerpt":"What is Thread? Life cycle of thread. Difference in start() and run() method of Thread. By Default how many thread runs?","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/1825","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/comments?post=1825"}],"version-history":[{"count":0,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/1825\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/media?parent=1825"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/categories?post=1825"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/tags?post=1825"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}