[go: up one dir, main page]

0% found this document useful (0 votes)
66 views1 page

Craete A Time Delay in Java

This document discusses using timers in Java to schedule tasks. The Timer class schedules TimerTask instances to run after a specified delay. An example Reminder class shows how to use a timer to print "Time's up!" 5 seconds after scheduling a RemindTask that extends TimerTask. When run, the output first confirms the task is scheduled, then 5 seconds later prints the message from the timed task.

Uploaded by

Man Runner
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views1 page

Craete A Time Delay in Java

This document discusses using timers in Java to schedule tasks. The Timer class schedules TimerTask instances to run after a specified delay. An example Reminder class shows how to use a timer to print "Time's up!" 5 seconds after scheduling a RemindTask that extends TimerTask. When run, the output first confirms the task is scheduled, then 5 seconds later prints the message from the timed task.

Uploaded by

Man Runner
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

This section discusses practical aspects of using timers to schedule tasks.

The Timer
class in the java.util package schedules instances of a class called TimerTask .
Reminder.java is an example of using a timer to perform a task after a delay:
import java.util.Timer;
import java.util.TimerTask;

/**
* Simple demo that uses java.util.Timer to schedule a task
* to execute once 5 seconds have passed.
*/

public class Reminder {


Timer timer;

public Reminder(int seconds) {


timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}

class RemindTask extends TimerTask {


public void run() {
System.out.println("Time's up!");
timer.cancel(); //Terminate the timer thread
}
}

public static void main(String args[]) {


new Reminder(5);
System.out.println("Task scheduled.");
}
}
When you run the example, you first see this:
Task scheduled.
Five seconds later, you see this:
Time's up!

You might also like