How to plan a task at periodic intervals?

I tried to use some codes to accomplish a planned task and came up with these codes.

import java.util.*; class Task extends TimerTask { int count = 1; // run is a abstract method that defines task performed at scheduled time. public void run() { System.out.println(count+" : Mahendra Singh"); count++; } } class TaskScheduling { public static void main(String[] args) { Timer timer = new Timer(); // Schedule to run after every 3 second(3000 millisecond) timer.schedule( new Task(), 3000); } } 

My conclusion:

 1 : Mahendra Singh 

I expected the compiler to print the Mahendra Singh series at 3-second intervals, but despite waiting about 15 minutes, I get only one result ... How to solve this?

+71
java timer schedule
Dec 28 '10 at 6:44
source share
7 answers

Use timer.scheduleAtFixedRate

 public void scheduleAtFixedRate(TimerTask task, long delay, long period) 

Schedules the specified task to re-execute the fixed rate, starting with the specified delay. Subsequent executions are carried out at approximately equal intervals divided by the specified period.
In a fixed-rate execution, each execution is planned relative to the planned execution time of the initial execution. If the execution is delayed for any reason (for example, garbage collection or other background activity), two or more executions will be executed in quick succession to β€œcatch up”. Ultimately, the frequency of execution will exactly coincide with the specified period (provided that the system clock underlying the Object.wait (long) is accurate).

Fixed rate execution is suitable for repetitive activities that are sensitive to absolute time, such as ringing at an o'clock every hour at an o'clock or daily scheduled maintenance at a specific time. Also suitable for repetitive actions when the total execution time of a fixed number of executions is important, such as a countdown timer that ticks once per second for ten seconds. Finally, performing fixed speed is suitable for scheduling multiple repeating timer tasks that must remain synchronized relative to each other.

Options:

  • task - the task should be planned.
  • delay - the delay in milliseconds before the task is completed.
  • period - in milliseconds between successive tasks.

Throws:

  • IllegalArgumentException - if the delay is negative or the delay + System.currentTimeMillis () is negative.
  • IllegalStateException - if the task has already been scheduled or canceled, the timer has been canceled or the time stream has ended.
+63
Dec 28 '10 at 8:01
source share

ScheduledExecutorService

I want to offer you an alternative to using a timer - ScheduledThreadPoolExecutor , an implementation of ScheduledExecutorService . It has some advantages over the Timer class (from "Java to Concurrency"):

A timer creates only one thread to perform timer tasks. If the timer task takes too much time to complete, the accuracy of the synchronization of other timer tasks may be affected. If the scheduled start of the TimerTask is scheduled every 10 ms, and another timer task takes 40 ms to start, the repeated task (depending on whether it was scheduled at a fixed speed or a fixed delay) is called four times in a row after a long terminating task is completed or completely misses four calls. Scheduled thread pools address this limitation, allowing you to provide multiple threads for pending and periodic tasks.

Another issue with Timer is that it behaves badly if TimerTask throws an exception. The Timer thread throws no exception, so an thrown exception from TimerTask terminates the timer thread. The timer also does not resurrect the thread in this situation; instead, he mistakenly assumes that the entire timer has been canceled. In this case, TimerTasks that are already scheduled but not yet completed never start, and new tasks cannot be scheduled. (This problem is called "thread leak").

And another recommendation, if you need to create your own scheduling service, you can still use the library using DelayQueue, an implementation of BlockingQueue that provides ScheduledThreadPoolExecutor scheduling functionality. DelayQueue manages a collection of Delayed objects. A Delayed has a delay time associated with it: DelayQueue allows you to take an item only if its delay time has expired. Objects are returned from the DelayQueue parameter, sorted by the time associated with their delay.

+68
Dec 28 '10 at 9:11
source share
 public void schedule(TimerTask task,long delay) 

Schedules the specified task for execution after the specified delay.

Do you want to:

 public void schedule(TimerTask task, long delay, long period) 

Schedules the specified task to perform a repeated fixed delay , starting with the specified delay. Subsequent executions are carried out at approximately regular intervals separated by a predetermined period.

+13
Dec 28 '10 at 6:54
source share

A quartz scheduler is also a solution, and firstly, you run the Quartz Job class.

Quartz task is defined that you want to run

 package com.blogspot.geekonjava.quartz; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobKey; public class QuartzJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { JobKey jobKey = context.getJobDetail().getKey(); System.out.println("Quartz" + "Job Key " + jobKey); } } 

Now you need to do Quartz Trigger

There are two types of triggers in Quartz

SimpleTrigger . Allows you to set the start time, end time, repetition interval.

 Trigger trigger = newTrigger().withIdentity("TriggerName", "Group1") .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(10).repeatForever()).build(); 

CronTrigger . Allows an unix cron expression to specify dates and to do its job.

 Trigger trigger = newTrigger() .withIdentity("TriggerName", "Group2") .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")).build(); 

The scheduler class links both the Work and the Trigger and executes it.

 Scheduler scheduler = new StdSchedulerFactory().getScheduler(); scheduler.start(); scheduler.scheduleJob(job, trigger); 

The full example you can see here

+4
May 26 '15 at 6:34
source share

You can use quartz

+3
Dec 28 '10 at 7:11
source share
 timer.scheduleAtFixedRate( new Task(), 1000,3000); 
+2
Mar 03 '16 at 7:54 on
source share

Java has a Timer and TimerTask class for this, but what is it?

  • java.util.Timer is a utility class that you can use to schedule a thread that will be executed at a specific time in the future. The Java Timer class can be used to schedule a task to be run at once or to run intervals on a regular basis.
  • java.util.TimerTask is an abstract class that implements the Runnable interface, and we need to extend this class to create our own TimerTask, which can be scheduled using the Java timer class.

You can check out the full tutorial from GeekonJava

 TimerTask timerTask = new MyTimerTask(); //running timer task as daemon thread Timer timer = new Timer(true); timer.scheduleAtFixedRate(timerTask, 0, 10*1000); 
+1
Apr 15 '15 at 7:02
source share



All Articles