schedule(TimerTask, long, long): This method is available in java.util.Timer class of Java.
Syntax:
void java.util.Timer.schedule(TimerTask task, long delay, long period)
This method takes three arguments. This method schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
Note: Subsequent executions take place at approximately regular intervals separated by the specified period.
Parameters: Three parameters are required for this method.
task: task to be scheduled.
delay: delay in milliseconds before the task is to be executed.
period: time in milliseconds between successive task executions.
Throws:
1. IllegalArgumentException - if delay < 0, or delay + System.currentTimeMillis() < 0, or period <= 0.
2. IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
3. NullPointerException - if task is null
Approach 1: When no exception
Java
import java.util.Timer;import java.util.TimerTask;public class Timerschedule4 {public static void main(String[] args) {Timer timer = new Timer();TimerTask timerTask = new TimerTask() {@Overridepublic void run() {System.out.println("Runner");}};long delay = 1000L;long period = 10000L;timer.schedule(timerTask, delay, period);}}
Output:
Runner Runner.....
Approach 2: IllegalArgumentException
Java
import java.util.Timer;import java.util.TimerTask;public class Timerschedule4 {public static void main(String[] args) {Timer timer = new Timer();TimerTask timerTask = new TimerTask() {@Overridepublic void run() {System.out.println("Runner");}};long delay = -1000L;long period = 10000L;timer.schedule(timerTask, delay, period);}}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Negative delay. at java.base/java.util.Timer.schedule(Timer.java:246)
Approach 3: IllegalStateException
Java
import java.util.Timer;import java.util.TimerTask;public class Timerschedule4 {public static void main(String[] args) {Timer timer = new Timer();TimerTask timerTask = new TimerTask() {@Overridepublic void run() {System.out.println("Runner");}};long delay = 1000L;long period = 10000L;timer.cancel();timer.schedule(timerTask, delay, period);}}
Output:
Exception in thread "main" java.lang.IllegalStateException: Timer already cancelled. at java.base/java.util.Timer.sched(Timer.java:398) at java.base/java.util.Timer.schedule(Timer.java:249)
Approach 4: NullPointerException
Java
import java.util.Timer;import java.util.TimerTask;public class Timerschedule4 {public static void main(String[] args) {Timer timer = new Timer();TimerTask timerTask = null;long delay = 1000L;long period = 10000L;timer.schedule(timerTask, delay, period);}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot read field "lock" because "task" is null at java.base/java.util.Timer.sched(Timer.java:400) at java.base/java.util.Timer.schedule(Timer.java:249)
No comments:
Post a Comment