{"id":4225,"date":"2019-05-10T13:26:20","date_gmt":"2019-05-10T17:26:20","guid":{"rendered":"http:\/\/springframework.guru\/?p=4225"},"modified":"2019-06-30T08:37:45","modified_gmt":"2019-06-30T12:37:45","slug":"java-timer","status":"publish","type":"post","link":"https:\/\/springframework.guru\/java-timer\/","title":{"rendered":"Java Timer"},"content":{"rendered":"<p><a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Timer.html\" target=\"_blank\" rel=\"noopener noreferrer\">Timer<\/a> is a utility class as a facility for Threads to schedule tasks for future execution as a background thread. You can use this class to schedule tasks for one-time execution or for repeated execution at a regular interval.<\/p>\n<p>In this post, I\u2019ll explain how to schedule tasks in Java applications using the <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Timer.html\" target=\"_blank\" rel=\"noopener noreferrer\">Timer<\/a> and <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/TimerTask.html\" target=\"_blank\" rel=\"noopener noreferrer\">TimerTask<\/a> classes.<\/p>\n<h2>Timer and TimerTask<\/h2>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> is used with <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code>, an abstract class which defines the task to be scheduled by <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code>. You need to extend <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code> to create a task that will be scheduled by <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code>. Java <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code> implements the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Runnable<\/code> interface.<\/p>\n<p>Each of the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code> is executed sequentially by a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> object which has a corresponding single background thread. <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code> objects should complete execution quickly. If a timer task takes too long to complete, it dominates the timer&#8217;s task execution thread, which in turn will delay the execution of the subsequent tasks. The tasks will finally accumulate into a queue.<\/p>\n<p>Note: Java <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> object can be shared by multiple threads without any external synchronization.<\/p>\n<p>A <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code> object remains in one of the following states.<\/p>\n<ul>\n<li><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">VIRGIN<\/code>: When a task is created, its initial state will be <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">VIRGIN<\/code><\/li>\n<li><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">SCHEDULED<\/code>: Once the task is picked up by <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> for execution, its state is changed to <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">SCHEDULED<\/code>.<\/li>\n<li><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">EXECUTED<\/code>: After execution its state becomes <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">EXECUTED<\/code>.<\/li>\n<li><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">CANCELLED<\/code>: If we call the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">cancel()<\/code> method on a task, the task goes into the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">CANCELLED<\/code> state. A task in the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">CANCELLED<\/code> state will never be picked up by the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> for execution.<\/li>\n<\/ul>\n<h2>Scheduling Tasks with Timer<\/h2>\n<p>Let\u2019s start coding and use <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> to schedule a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code>.<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">MyTask<\/code> is a Java class that defines its own task by extending <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code>.<\/p>\n<h5>MyTask.java<\/h5>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package springframework.guru.javatimer.task;\r\n\r\nimport java.util.Date;\r\nimport java.util.TimerTask;\r\n\r\npublic class MyTask extends TimerTask {\r\n   @Override\r\n   public void run() {\r\n       System.out.println(\"Start of mytask at \" + new Date());\r\n       timeConsumingTask();\r\n       System.out.println(\"End of mytask at \" + new Date());\r\n   }\r\n   public void timeConsumingTask() {\r\n       try {\r\n           Thread.sleep(20000);\r\n       }catch (InterruptedException ex) {\r\n           ex.printStackTrace();\r\n       }\r\n   }\r\n}<\/pre>\n<p>To define your own <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code> you need to override the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">run()<\/code> method of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code>. Here we have assumed that the task will take 20 seconds to complete.<\/p>\n<p>Next we will schedule the defined task.<\/p>\n<h3>Scheduling a Task to Run Once<\/h3>\n<p>I have written a JUnit test class to run the task we defined with the help of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code>. If you are new to JUnit, I suggest going through my series of <a href=\"http:\/\/springframework.guru\/unit-testing-junit-part-1\/\" target=\"_blank\" rel=\"noopener noreferrer\">JUnit posts<\/a>.<\/p>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">MyTaskTest<\/code> class is this.<\/p>\n<p>MyTaskTest.java<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package springframework.guru.javatimer.task;\r\n\r\nimport org.junit.After;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\n\r\nimport java.util.Date;\r\nimport java.util.Timer;\r\n\r\npublic class MyTaskTest {\r\n   MyTask myTask;\r\n   Timer timer;\r\n\r\n   @Before\r\n   public void setUp() {\r\n       myTask = new MyTask();\r\n       timer = new Timer(true);\r\n   }\r\n\r\n   @After\r\n   public void tearDown() {\r\n       myTask = null;\r\n       timer = null;\r\n   }\r\n\r\n   @Test\r\n   public void schedulingTaskOnce() {\r\n       long delay = 1000L;\r\n       timer.schedule(myTask, delay*10);\r\n       System.out.println(\"MyTask begins!!\" + new Date());\r\n       try {\r\n           Thread.sleep(60000);\r\n       } catch (InterruptedException e) {\r\n           e.printStackTrace();\r\n       }\r\n   }\r\n}<\/pre>\n<p>In the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">@Setup<\/code> method, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer(true)<\/code> creates a new <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> whose associated thread can be run as a daemon thread. You can also use the overladed <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer(String name)<\/code> constructor to create a timer whose thread has the specified name.<\/p>\n<p>In the test case, the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">timer.schedule()<\/code> method schedules the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code> to execute after a delay of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">10,000<\/code> ms.<\/p>\n<p>Once the timer schedules the task, the code instructs the timer\u2019s thread to sleep for <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">60<\/code> seconds.<\/p>\n<p>The output on running the tests in IntelliJ is this.<br \/>\n<a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_once.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-large wp-image-4226\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_once-1024x164.png\" alt=\"Test Output Scheduling Once\" width=\"863\" height=\"138\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_once-1024x164.png 1024w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_once-300x48.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_once-768x123.png 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_once.png 1280w\" sizes=\"(max-width: 863px) 100vw, 863px\" \/><\/a><\/p>\n<h3>Scheduling a Repeated Task on a Regular Interval<\/h3>\n<p>You can use the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">scheduleAtFixedRate()<\/code> method of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> to schedule the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code> periodically with a specific interval.<\/p>\n<p>This code snippet schedules the task with a delay of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">1000<\/code> ms and to repeat after every <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">500<\/code> ms.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Test\r\n   public void schedulingTaskAtRepeatedInterval() {\r\n       long delay = 1000L;\r\n       long period = 1000L;\r\n       timer.scheduleAtFixedRate(myTask, delay, period);\r\n       System.out.println(\"MyTask begins and repeats at a specific interval!!\" + new Date());\r\n       try {\r\n           Thread.sleep(60000);\r\n       } catch (InterruptedException e) {\r\n           e.printStackTrace();\r\n       }\r\n   }<\/pre>\n<p>The output on running the tests in IntelliJ is this.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_repeated_interval.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-large wp-image-4227\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_repeated_interval-1024x240.png\" alt=\"\" width=\"863\" height=\"202\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_repeated_interval-1024x240.png 1024w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_repeated_interval-300x70.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_repeated_interval-768x180.png 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_repeated_interval.png 1278w\" sizes=\"(max-width: 863px) 100vw, 863px\" \/><\/a><\/p>\n<h3>Scheduling a Task to Run Once a Day<\/h3>\n<p>Consider you need to schedule a task to run once a day. One approach is to call the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">scheduleAtFixedRate() <\/code> method passing the appropriate delay and period parameters like this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Test\r\npublic void schedulingTaskDaily() {\r\n   long delay = 1000L;\r\n   long period = 1000L * 60L * 60L * 24L;\r\n   timer.scheduleAtFixedRate(myTask, delay, period);\r\n   System.out.println(\"MyTask begins and repeats every day!!\" + new Date());\r\n   try {\r\n       Thread.sleep(30000);\r\n   } catch (InterruptedException e) {\r\n       e.printStackTrace();\r\n   }\r\n}<\/pre>\n<p>The output on running the test in IntelliJ is this.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_daily.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-large wp-image-4228\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_daily-1024x148.png\" alt=\"\" width=\"863\" height=\"125\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_daily-1024x148.png 1024w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_daily-300x43.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_daily-768x111.png 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_scheduling_daily.png 1277w\" sizes=\"(max-width: 863px) 100vw, 863px\" \/><\/a><\/p>\n<p>Another approach is to use the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer.schedule(TimerTask task, Date firstTime, long period)<\/code> method.<\/p>\n<h2>Cancelling Timer and TimerTask<\/h2>\n<p>At times you might need to cancel a running <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code>. One way is to invoke the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">cancel()<\/code> method on the timer. The second way is to call the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">cancel()<\/code> method on the thread that runs the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code>.<\/p>\n<p>Call <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">cancel()<\/code> on the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> if that&#8217;s all it is doing. On the other hand, if the timer itself has other tasks which you wish to continue, call the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">cancel()<\/code> method on the thread running <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code> like this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">public void run() {\r\n   System.out.println(\"Start of mytask at \" + new Date());\r\n   timeConsumingTask();\r\n   System.out.println(\"End of mytask at \" + new Date());\r\n   cancel();\r\n}<\/pre>\n<p>The test code is this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Test\r\npublic void checkCancelOfTimerTask() {\r\n   long delay = 1000L;\r\n   long period = 1000L;\r\n   timer.scheduleAtFixedRate(myTask, delay, period);\r\n   System.out.println(\"MyTask begins and repeats at a specific interval and then cancels!!\" + new Date());\r\n   try {\r\n       Thread.sleep(60000);\r\n   } catch (InterruptedException e) {\r\n       e.printStackTrace();\r\n   }\r\n}<\/pre>\n<p>The output on running the tests in IntelliJ is this.<br \/>\n<a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer-task.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-large wp-image-4229\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer-task-1024x155.png\" alt=\"\" width=\"863\" height=\"131\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer-task-1024x155.png 1024w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer-task-300x45.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer-task-768x116.png 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer-task.png 1277w\" sizes=\"(max-width: 863px) 100vw, 863px\" \/><\/a><\/p>\n<p>Note that when you call the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">cancel()<\/code> method within the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">run()<\/code> method of a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TimerTask<\/code> that was invoked by this <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code>, it guarantees that the ongoing task will be the last task executed by the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code>. It takes a minute and above to terminate the test since we have given <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">60<\/code> seconds to stop the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> thread.<\/p>\n<p>On the other hand, the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">cancel()<\/code> method on <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> terminates the timer discarding any currently scheduled tasks. The executing thread terminates once the timer is terminated and no more tasks can be scheduled on the cancelled timer.<\/p>\n<p>The test code for calling <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">cancel()<\/code> on the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> is this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Test\r\npublic void checkCancelOnTimerObject() {\r\n   long delay = 1000L;\r\n   long period = 1000L;\r\n   timer.scheduleAtFixedRate(myTask, delay, period);\r\n   System.out.println(\"MyTask begins and repeats at a specific interval!!\" + new Date());\r\n   try {\r\n       Thread.sleep(4000);\r\n   } catch (InterruptedException e) {\r\n       e.printStackTrace();\r\n   }\r\n   timer.cancel();\r\n   System.out.println(\"Timer cancelled\");\r\n}<\/pre>\n<p>Here we specify the sleep time for the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Timer<\/code> thread because we are running the code snippet as a JUnit test case. Hence we must call <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Thread.Sleep(delay*n)<\/code> to allow the Timer\u2019s thread to run the task before the JUnit test stops executing.<\/p>\n<p>Let us change the sleep time of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">MyTask<\/code> to <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">1<\/code> second to check if the timer is cancelled.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">public void timeConsumingTask() {\r\n  try {\r\n      Thread.sleep(1000);\r\n  }catch (InterruptedException ex) {\r\n      ex.printStackTrace();\r\n  }\r\n}<\/pre>\n<p>The output on running the tests in IntelliJ is this.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-large wp-image-4230\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer-1024x210.png\" alt=\"\" width=\"863\" height=\"177\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer-1024x210.png 1024w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer-300x61.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer-768x157.png 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/test_output_cancel_timer.png 1275w\" sizes=\"(max-width: 863px) 100vw, 863px\" \/><\/a><\/p>\n<h2>Summary<\/h2>\n<p>The built-in Timer is adequate for scheduling tasks in small to mid-size Java applications. When you are developing Spring applications, you can also use the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TaskExecutor<\/code> and <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">TaskScheduler<\/code> interfaces that the Spring Framework brings in.<\/p>\n<p>However, for large-scale enterprise application development using Spring Boot, you need a more comprehensive scheduling solution.<\/p>\n<p><a href=\"http:\/\/www.quartz-scheduler.org\/\" target=\"_blank\" rel=\"noopener noreferrer\">Quartz<\/a> is one open source job scheduling library with rich enterprise-class features including JTA transactions and clustering. Spring Boot provides the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">spring-boot-starter-quartz<\/code> &#8220;Starter&#8221; to get you quickly up and running with Quartz.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Timer is a utility class as a facility for Threads to schedule tasks for future execution as a background thread. You can use this class to schedule tasks for one-time execution or for repeated execution at a regular interval. In this post, I\u2019ll explain how to schedule tasks in Java applications using the Timer and [&hellip;]<a href=\"https:\/\/springframework.guru\/java-timer\/\" class=\"df-link-excerpt\">Continue reading<\/a><\/p>\n","protected":false},"author":111,"featured_media":4592,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[20],"tags":[],"class_list":["post-4225","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"jetpack_publicize_connections":[],"aioseo_notices":[],"modified_by":"Simanta","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/springframework.guru\/wp-content\/uploads\/2015\/03\/Banner560x292_07web.jpg","jetpack_shortlink":"https:\/\/wp.me\/p5BZrZ-169","_links":{"self":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/4225"}],"collection":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/users\/111"}],"replies":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/comments?post=4225"}],"version-history":[{"count":10,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/4225\/revisions"}],"predecessor-version":[{"id":5749,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/4225\/revisions\/5749"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media\/4592"}],"wp:attachment":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media?parent=4225"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/categories?post=4225"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/tags?post=4225"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}