neither scheduleAtFixedRate
nor scheduleWithFixedDelay
methods can directly meet your business needs
, but you can use scheduleAtFixedRate
to indirectly meet your requirements. You can first estimate a time interval, which can be set to 5 minutes, and check whether it is the time in the list every five minutes. If so, execute the business. Because your tasks are not very frequent, you can use the single thread pool
code as follows:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleWithFixedDelay(() -> {
//
}, 10L, 5L, TimeUnit.MINUTES);
Update:
after considering it, you can do it with sleep
or wait
. Specifically, every time you take out a time in the list, you can calculate the millisecond value from the current time, and then call TimeUnit.MILLISECONDS.sleep ()
to sleep. The disadvantage of this method is that due to the uncertainty of cpu scheduling, the time point that may be executed is not particularly accurate, which can be used for businesses with low requirements. spring, quartz
is actually scheduling thread pool or jdk1.3
previous Timer
task scheduling, there is no essential difference, and it is not suitable for this change to schedule tasks. In addition, what is said downstairs is also true, but overqualified personnel are overused, and there is no need to use multi-thread pools or even thread pools
.
the main idea of the building is correct, but there is no need for you to cancel. ScheduledExecutorService
itself maintains a delayed task queue, and the task can be one-time, while the list
of the subject can be converted into a delay queue (time span from the current time). The list
change is to maintain the elements in the delay queue. ScheduledExecutorService
has been provided to API to add elements to the queue:
/**
* Creates and executes a one-shot action that becomes enabled
* after the given delay.
*
* @param command the task to execute
* @param delay the time from now to delay execution
* @param unit the time unit of the delay parameter
* @return a ScheduledFuture representing pending completion of
* the task and whose {@code get()} method will return
* {@code null} upon completion
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if command is null
*/
public ScheduledFuture<?> schedule(Runnable command,
long delay, TimeUnit unit);
you can add all the elements of list
to the delayed task queue, or you can add the next task to the delayed queue after each task ends. As long as the former sets appropriate corePoolSize
, there will be no conflict between tasks, while the latter has the problem of task conflict. For example, Task 1
is very time-consuming, Task 2
can not be executed until Task 1
is completed.