Timer in Java
Timer in Java is available in java. util package extends Object class and implements Serializable and Cloneable interfaces. The timer class contains methods that are used to perform timing-related activities. Timer Class in Java is used for performing time-related scheduling of tasks. Java threads use the Timer class’s methods to schedule a task like executing a section of code after some instant of time, repeated execution of code after some predefined time. Each Timer object is bound to a separate background running thread which is responsible for executing all tasks associated with the thread. It is to be noted that the timer class in java is thread-safe; that is, at a time, only one thread can execute the Timer class method. Also Timer class makes use of binary heap as an underlying data structure to store tasks.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax of Timer in Java
Here is a basic syntax of how the Timer class is used in java:
Syntax:
// create a class extending TimerTask class TimerHelper extends TimerTask { //define run method public void run() { // Write Code to be executed by Timer } } class MainClass{ public static void main(String[] args) { //create timer instance Timer timer = new Timer(); // create Timer class instance TimerTask task = new TimerHelper (); // call timer method timer.schedule(task, 3000,6000); //first argument is timer object // second argument is time in milliseconds after which the code will be first executed // Third argument is time in milliseconds after which the code will be executed regularly. } }
Explanation of the above syntax: The syntax shows how a Timer class is used in java. Using a timer class involves creating a class extending TimerTask and defining the run method in it. The run method contains logic that needs to be executed on a time-driven basis. Below is the Timer class declaration:
public class Timer extends Object implements Serializable, Cloneable
Methods of Timer Class in Java
Now we will see what different methods and fields available in the java Timer class are. Here is the list of commonly used methods available in Timer class:
|
Description | ||||||||||||||||||
public void schedule(TimerTask task, Date date) | Schedules a task to be executed on the defined date. | ||||||||||||||||||
public void schedule (TimerTask task, Date firstTime, long timeperiod) | The first argument is TimerTask to be executed; the second argument is the time after which the task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly. | ||||||||||||||||||
public int purge() | Used for removing all canceled tasks from the timer’s queue. | ||||||||||||||||||
public void cancel() | Cancel’s the timer. | ||||||||||||||||||
public void schedule(TimeTask task, long delay) | Schedules the task to be executed after the specified time in milliseconds. | ||||||||||||||||||
public void schedule(TimeTask task, long delay, long period) | The first argument is TimerTask to be executed; the second argument is the time in milliseconds after which task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly. | ||||||||||||||||||
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long timeperiod) | The first argument is TimerTask to be executed; the second argument is the time after which the task is executed for the first time, and the third argument is seconds in milliseconds after which the task will be executed regularly. | ||||||||||||||||||
public void scheduleAtFixedRate (TimeTask task, long delay, long period) | The first argument is TimerTask to be executed; the second argument is the time in milliseconds after which task is executed for the first time, and the third argument is seconds in milliseconds after which task will be executed regularly. |
From the above-stated methods, we have found two methods that are similar in working but different in the name; they are schedule and scheduleAtFixedRate. The difference between the two is that in the case of fixed-rate execution, each execution is scheduled in accordance with the initial execution. If there is a delay in execution, then two or more executions will occur in quick succession to overcome the delay.
Constructors in Timer Class
The timer class contains four constructors for instantiating timer object.
- Timer(): Creates a new Timer Object.
- Timer(boolean isDaemon): Creates a timer object with a corresponding thread specified to run as a daemon.
- Timer(String name): Creates a timer object with a corresponding thread name.
- Timer(String name, boolean isDaemon): This method is a combination of the above two constructors.
One of the above four listed constructors can be called depending on our requirements.
Examples of Implementing Timer in Java
Below is the example of Timer in Java:
Example #1
To start things, let us see a basic example of Timer class. In this example, we will demonstrate the use of the schedule method of the Timer class.
Code:
package com.edubca.timer; import java.util.Timer; import java.util.TimerTask; class TimerHelper extends TimerTask { public static int counter = 0; public void run() { counter++; System.out.println("Timer run Number " + counter); } } public class Main { public static void main(String[] args) { Timer timer = new Timer(); TimerTask timerhelper = new TimerHelper(); timer.schedule(timerhelper, 3000, 2000); } }
Explanation of the above code: The above code will execute the run method for the first time after 3 seconds as the first argument is 3000, and after every 2 seconds, the run method will be executed regularly. Here is the output that will be displayed:
Output:
Example #2
In this example, we will see how to terminate a timer thread after a given number of timer runs.
Code:
package com.edubca.timer; import java.util.Timer; import java.util.TimerTask; class TimerHelper extends TimerTask { public static int counter = 0; public void run() { counter++; if(counter ==3){ this.cancel(); System.out.println("Now Cancelling Thread!!!!!"); return; } System.out.println("Timer run Number " + counter); } } public class Demo { public static void main(String[] args) { Timer timer = new Timer(); TimerTask helper = new TimerHelper(); helper.schedule(task, 3000, 2000); } }
In the above example, the timer will cancel after the three times run method is called using the timer class’s cancel method.
Output:
The above is the detailed content of Timer in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
