A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/java/util/java_util_timer.htm below:

Java Timer Class

Java Timer Class Introduction

The Java Timer class provides facility for threads to schedule tasks for future execution in a background thread.

Class declaration

Following is the declaration for java.util.Timer class −

public class Timer
   extends Object
Class constructors Sr.No. Constructor & Description 1

Timer()

This constructor creates a new timer.

2

Timer(boolean isDaemon)

This constructor creates a new timer whose associated thread may be specified to run as a daemon.

3

Timer(String name)

This constructor creates a new timer whose associated thread has the specified name.

4

Timer(String name, boolean isDaemon)

This constructor creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon.

Class methods Methods inherited

This class inherits methods from the following classes −

Scheduling a Task to Execute using Timer Example

The following example shows the usage of Java Timer schedule(TimerTask, Date) method to schedule a timer operation. We've created a timer object using a CustomTimerTask object. CustomTimerTask is custom class extending TimerTask class and implements the run() method which will execute at scheduled time. Then we created a timer object and scheduled a task using schedule() to execute task now.

package com.tutorialspoint;

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

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

      // creating timer task, timer
      TimerTask tasknew = new CustomTimerTask();
      Timer timer = new Timer("test",true);

      // scheduling the task
      timer.schedule(tasknew, new Date()); 

      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         System.out.println("Error");
      }
   }
}

class CustomTimerTask extends TimerTask {

   @Override
   public void run() {
      System.out.println("working on");
   }  
}

Output

Let us compile and run the above program, this will produce the following result.

working on

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4