Wednesday, 30 January 2019

Timer and TimerTask Introduction | How to schedule a task once using Timer and TimerTask


Click here to watch on Youtube:
https://www.youtube.com/watch?v=j0UdOx1tRzg&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge:
Timer and TimerTask Introduction | How to schedule a task once using Timer and TimerTask

Timer and TimerTask Introduction | How to schedule a task once using Timer and TimerTask

Timer and TimerTask Introduction | How to schedule a task once using Timer and TimerTask

CleanUpTimerTask.java

import java.util.TimerTask;

public class CleanUpTimerTask extends TimerTask
{
    public void run()
    {
        System.out.println("Clean up files...");
    }
}

TimerDemo.java

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerDemo
{
    public static void main(String[] args)
    {

        /*
         * Creating timer task
         */

        TimerTask cleanUpTimerTask = new CleanUpTimerTask();

        /*
         * Creates a new timer. The associated thread does not run as
         * a daemon.
         */

        Timer timer = new Timer();

        Date scheduleDateTime = new Date(System.currentTimeMillis() + 20000);
        System.out.println("scheduleDateTime = " + scheduleDateTime);

        /*
         * Schedules the specified task for execution at the specified
         * time. If the time is in the past, the task is scheduled for
         * immediate execution.
         *
         * Parameters:
         *
         * task - task to be scheduled.
         *
         * time - time at which task is to be executed.
         */

        timer.schedule(cleanUpTimerTask, scheduleDateTime);
        System.out.println("Timer has schedule the -------cleanUpTimerTask...");
    }

}

Output:

scheduleDateTime = Mon Jan 14 10:15:02 IST 2019
Timer has schedule the -------cleanUpTimerTask...
Clean up files...

Refer: 

https://docs.oracle.com/javase/8/docs/api/index.html?java/util/TimerTask.html

https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Timer.html

Click the below link to download the code:
https://sites.google.com/site/javaspringram2019/java_spring_2019/TimerDemo_Intro.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java_Spring_2019/tree/master/Java_2019/TimerDemo_Intro

Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/2db5cd1f4e7d5ab55ad7af886d6164700143c614/Java_2019/TimerDemo_Intro/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • No comments:

    Post a Comment