What’s Timer and TimerTask in Java – Tutorial Instance

Advertisements

[ad_1]

Timer in Java is a utility class that’s used to schedule duties for each
one time and repeated execution.
Timer is comparable
to the alarm facility many individuals use in cellphones. Identical to you possibly can have one
time alarm or repeated alarm, You should use
java.util.Timer to
schedule a time job or repeated job. The truth is, we will implement a
Reminder utility
utilizing Timer in Java and that is what we’re going to see on this instance of
Timer in Java. Two courses java.util.Timer and java.util.TimerTask is used to
schedule jobs in Java and varieties Timer API. 
The TimerTask is an precise job that’s executed by Timer. Much like Thread in JavaTimerTask additionally implements the Runnable interface and overrides run methodology to specify a job particulars. 


This Java tutorial may also spotlight the distinction between Timer and TimerTask class and explains how Timer
works in Java. By the best way, the distinction between Timer and Thread can be a widespread
Java questions on fresher-level interviews.

What’s Timer and TimerTask in Java

Timer in Java is a utility class from java.util bundle
which supplies the power to schedule duties at any time sooner or later. As I stated
earlier,
Timer is analog to the alarm clock you arrange in your smartphone. 


Identical to alarm might be both one time or recurring, You may as well schedule job
for one time and recurring time interval utilizing Timer API. Timer supplies methodology
to schedule Job the place the duty is an occasion of
TimerTask class,
which implements the 
Runnable interface and overrides run() methodology to
outline job which is named on scheduled time.

How Timer works in Java?

Timer class in Java maintains a background Thread (this could possibly be either daemon thread or person thread,
primarily based on the way you created your Timer object), additionally referred to as timer’s job
execution thread. For every Timer, there can be a corresponding job processing Thread that runs the scheduled
job on the specified time. 



In case your Timer thread just isn’t daemon then it’ll cease
your utility from exits till it completes all scheduled duties. It is
really useful that TimerTask shouldn’t be very lengthy in any other case it could possibly preserve
this thread busy and never permit different scheduled duties to get accomplished. 



This could
delay the execution of different scheduled duties, which can queue up and execute in
fast succession as soon as the offending job is accomplished.

Here’s a good diagram which illustrate how Timer works in Java:

Distinction between Timer and TimerTask in Java

I’ve seen programmers getting confused between Timer and TimerTask, which is
fairly pointless as a result of these two are altogether totally different. You simply must
keep in mind:

1) Timer in Java schedules and execute TimerTask which is
an implementation of Runnable interface and overrides
run methodology to outline the precise job carried out by that
TimerTask.

2) Each Timer and TimerTask present a cancel() methodology. Timer’s
cancel() methodology cancels the entire timer whereas TimerTask’s one cancels solely a
specific job. I believe that is the price noting distinction between
Timer and TimerTask in Java.

Additionally, here’s a good desk which highlights all of the distinction between Timer and TimerTask in Java:

Canceling
Timer in Java

You may cancel Java Timer by calling the cancel() methodology of java.util.Timer class,
this is able to outcome within the following:

1) Timer won’t cancel any presently executing job.

2) Timer will discard different scheduled duties and can
not execute them.

3) As soon as the presently executing job shall be completed, the timer thread will
terminate gracefully.

4) Calling Timer.cancel() a couple of time won’t
have an effect on. the second name shall be ignored.

Along with canceling Timer, You may as well cancel
particular person
TimerTask by utilizing the cancel() methodology of TimerTask itself. You may additional see these Java Multithreading programs to be taught extra about Thread and TimerTask in Java. 

Timer
and TimerTask instance to schedule Duties

Right here is one instance of Timer and TimerTask in Java to implement Reminder
utility.

public class JavaReminder {

    Timer timer;

    public JavaReminder(int seconds) {

        timer = new Timer();  //At this line a brand new Thread shall be
created

        timer.schedule(new RemindTask(), seconds*1000); //delay in
milliseconds

    }

    class RemindTask extends TimerTask {

        @Override

        public void run() {

            System.out.println(“ReminderTask
is accomplished by Java timer”
);

            timer.cancel(); //Not vital
as a result of we name System.exit

            //System.exit(0);
//Stops the AWT thread (and every thing else)

        }

    }

    public static void major(String args[]) {

        System.out.println(“Java
timer is about to begin”
);

        JavaReminder
reminderBeep
= new JavaReminder(5);

        System.out.println(“Remindertask
is scheduled with Java timer.”
);

    }

}

Output

Java timer is about to begin

Remindertask is scheduled with a Java timer.

ReminderTask is accomplished by Java timer  //it will print after 5 seconds

Essential
factors on Timer and TimerTask in Java

Timer and TimerTask example in JavaNow we all know what’s Timer and TimerTask in Java,
Tips on how to use them, Tips on how to cancel then and received an understanding of How Timer works
in Java. It’s a superb time to revise the 
Timer and TimerTask.

1. One Thread shall be created corresponding ot every Timer in Java, which may
be both daemon or person thread.

2.You may schedule a number of TimerTask with one
Timer.

3.You may schedule duties for both one-time execution or recurring
execution.

4.TimerTask.cancel() cancels solely that
specific job, whereas
Timer.cancel() cancel all job scheduled in
Timer.

5. Timer in Java will throw IllegalStateException when you attempt
to schedule a job on a Timer that has been canceled or whose Job execution Thread
has been terminated.

That is all on what’s Timer and TimerTask in Java
and the distinction between
Timer and TimerTask in Java. A superb understanding of Timer API is required by Java programmers to take most
benefit of scheduling options supplied by Timer. They’re important and might
be utilized in quite a lot of methods e.g. to periodically take away clear cache,  to carry out well timed jobs, and many others.

Different Java Multithreading Tutorials from Javarevisited Weblog



[ad_2]