Advanced Java: Timer and Timer Task

Seyed Sahil
2 min readSep 3, 2019

--

Hello there and welcome to my new tutorial. Today we will be discussing two utility classes of Java programming language Timer and TimerTask respectively. Going forward we will see one simple program which demonstrates the use case of these two classes.

Why are we using a timer? The answer to this question is simple to wait for certain activity or certain things for a given time period.

What are we going to do after time out? We do the activity which is planned after the timeout or handle the things we waited for.

The above utility classes are used for the exact same thing. The Timer keeps waiting for a certain amount of time and TimerTask gets executed after the timeout.

Please find below a sample program. It is easy to understand.

Scenario

Consider an online examination scenario where the session is active for a given amount of time. Once the time is over we lock the user from answering any questions and then save the session data and send it back to the server. Once that is done we show a message saying exam time is over.

Solution

For setting a timer, we will create a Timer instance and then use it to schedule a TimerTask. Once the timeout happens the TimerTask gets executed and it will do the session save and sending data back to server etc. The student answering is simulated using another thread which in every one-second answer the questions.

Code

Demo program for Timer and TimerTask usage

I hope you guys got a high-level overview of what a Timer and TimerTask utility class is and how they are used. Please post your questions or suggestions here.

Thank you

Happy Coding.

Originally published at http://sydlabz.wordpress.com on September 3, 2019.

--

--

Seyed Sahil
Seyed Sahil

Written by Seyed Sahil

Coding Since 2011, Software Engineer, Game Developer, Artist, Photographer. Passionate about Security and Web Technologies. Favourites — C, Java, Javascript.

No responses yet