Java Timer schedule() method

The schedule (TimerTask task, Date time) method of Timer class is used to schedule the task for execution at the given time. If the time given is in the past, the task is scheduled at that movement for execution.

Syntax

Parameter

task - it is the task to be scheduled.

time - it is the time in which task is to be executed.

Throws

IllegalArgumentException -It throws the exception when time.getTime() is negative.

IllegalStateException - It throws the exception when the task is scheduled or canceled, or when the timer is canceled, or when the timer thread is terminated.

NullPointerException - It throws the exception when task or time is null.

Example 1

Output:

Task is on

Example 2

Output:

working on
working on
working on
working on
working on
working on
working on
working on
working on
working on

Java Timer schedule(TimerTask task, Date firstTime, long period) Method

The schedule (TimerTask task, Date firstTime, long period) is the method of Timer class. It is used to schedule the given task again and again in given fixed time execution.

Syntax

Parameter

task - It is the task that is scheduled.

firstTime - It is the First time in which given task is executed.

period - It is the time in milliseconds execution.

Throws

IllegalArgumentException - It throws the exception when firstTime.getTime() is less than 0, or period is greater than or equal to 0

IllegalStateException - It throws the exception when the task is already scheduled or canceled, or when the timer is canceled, or when timer thread is terminated.

NullPointerException - It throws the exception when task or time is null.

Example 3

Output:

working on
working on
working on
working on
.
.
.
.
.

Example 4

Output:

working on
working on
working on
working on
.
.
.
.
.

Next TopicJava-timertask