
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
One of the methods in the Timer class is the void schedule(Timertask task, Date time) method. This method schedules the specified task for execution at the specified time. If the time is in the past, it schedules the task for immediate execution.
Declaration −The java.util.Timer.schedule(Timertask task, Date time) is declared as follows −
public void schedule(Timertask task, Date time)
There are few exceptions thrown by the schedule(Timertask task, Date time) method. They are as follows −
IllegalArgumentException | This exception is thrown if time.getTime() 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 or time is null. |
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, new Date()); // scheduling the task } public void run() { System.out.println("Performing the given task"); } }
Output
Task is running
Advertisements