- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Schedule a task for repeated fixed delay execution in Java
- Schedule a task for execution in Java after a given delay
- How to schedule tasks in Java to run for repeated fixed-delay execution, beginning at the specified time
- How to schedule tasks in Java to run for repeated fixed-delay execution, beginning after the specified delay
- How to schedule tasks in Java to run for repeated fixed-rate execution, beginning after the specified delay
- How to schedule tasks in Java to run for repeated fixed-rate execution, beginning at the specified time
- How to measure execution time for a Java method?
- Cancel the Timer Task in Java
- Get execution stats in MongoDB for a collection
- What is execution engine in JAVA?
- How do I time a method execution in Java
- How to create a Scheduled task with a task scheduler using PowerShell?
- Call the run() method of the Timer Task in Java
- Compilation and execution of Java Program
- How to calculate elapsed/execution time in Java?

Advertisements