
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Schedule a Task for Execution in Java After a Given Delay
One of the methods in the Timer class is the void schedule(Timertask task, long delay) method. This method schedules the specified task for execution after the specified delay.
Declaration −The java.util.Timer.schedule(Timertask task, long delay) is declared as follows −
public void schedule(Timertask task, long delay)
There are few exceptions thrown by the schedule(Timertask task, long delay) method. They are as follows −
IllegalArgumentException | This exception is thrown if delay is negative, or delay + System.currentTimeMillis() is negative. |
IllegalStateException | This exception is thrown if task was scheduled or cancelled beforehand, timer was cancelled, or timer thread terminated. |
NullPointerException | This exception is thrown if the task is null. |
Let us see a program illustrating the use of the void schedule(TimerTask task, long delay) method −
Example
import java.util.*; class MyTask extends TimerTask { public void run() { System.out.println("Task is running"); } } public class Example { public static void main(String[] args) { Timer timer = new Timer(); // creating timer TimerTask task = new MyTask(); // creating timer task timer.schedule(task,3000); // scheduling the task after the delay } public void run() { System.out.println("Performing the given task"); } }
Output
Task is running
Advertisements