Schedule Events with The Timer Class

Schedule Events with The Timer Class

Scheduling recurrent or future events can be a hassle, but the Timer class can make it a lot easier. With a couple of simple calls, you can create any number of scheduled or recurring events.

Timers are created with a simple constructor and then called with one of the schedule() methods to set an actual task. Tasks are defined by subclassing the TimerTask class and implementing a run() method that will be called when the scheduled event is reached. TimerTask implementations can be anonymous, as is done in this example:

 java.util.Timer timer = new java.util.Timer();java.util.TimerTask task = new java.util.TimerTask()   public void run() {/*insert task code here*/}   };

You can create three types of schedules: delay schedules, repeating schedules, and fixed-delay schedules. Delay schedules simply prompt an event to occur once at a specific future time. The code snippet below illustrates a task being scheduled to execute after 10 seconds have elapsed:


Repeating or fixed-rate schedules will prompt events to repeat once per each elapsed period (even if that means that tasks will queue up) and ensure that all events occur as closely as possible to their scheduled times. For example, the following code snippet creates a schedule that will execute its task once for every elapsed second, starting immediately:


A fixed-delay timer places the emphasis on ensuring that the indicated delay always elapses between invocations. This example will schedule a task to recur with at least a second delay between invocations, starting immediately:


Each Timer instance runs its tasks in a single thread, so if you want tasks to execute completely independently, you should create a new Timer object for each task. You can assign multiple tasks to a single Timer, but only one task can run at once. Therefore, multiple timer tasks can delay each other from their scheduled execution times.

See also  Using Consumer Trust to Help Build Brands On Major Social Platforms

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist