[英]How to stop a Runnable scheduled for repeated execution after a certain number of executions
我有一個Runnable。 我有一個類,使用ScheduledExecutorService和scheduleWithFixedDelay來調度此Runnable以執行。
我想改變這個班安排了Runnable固定延遲執行無限期 , 或直至它已經運行一定的次數,取決於被傳遞給構造函數的參數一些。
如果可能的話,我想使用相同的Runnable,因為它在概念上應該是“運行”相同的東西。
有兩個Runnables,一個在多次執行后(它保持計數)取消計划,另一個不執行:
public class MyClass{
private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
public enum Mode{
INDEFINITE, FIXED_NO_OF_TIMES
}
public MyClass(Mode mode){
if(mode == Mode.INDEFINITE){
scheduler.scheduleWithFixedDelay(new DoSomethingTask(), 0, 100, TimeUnit.MILLISECONDS);
}else if(mode == Mode.FIXED_NO_OF_TIMES){
scheduler.scheduleWithFixedDelay(new DoSomethingNTimesTask(), 0, 100, TimeUnit.MILLISECONDS);
}
}
private class DoSomethingTask implements Runnable{
@Override
public void run(){
doSomething();
}
}
private class DoSomethingNTimesTask implements Runnable{
private int count = 0;
@Override
public void run(){
doSomething();
count++;
if(count > 42){
// Cancel the scheduling.
// Can you do this inside the run method, presumably using
// the Future returned by the schedule method? Is it a good idea?
}
}
}
private void doSomething(){
// do something
}
}
我寧願只有一個Runnable來執行doSomething方法。 將調度綁定到Runnable感覺不對。 你怎么看待這件事?
有一個Runnable用於執行我們想要定期運行的代碼。 有一個單獨的調度runnable,用於檢查第一個Runnable運行的次數,並在達到一定量時取消。 這可能不准確,因為它是異步的。 感覺有點麻煩。 你怎么看待這件事?
擴展ScheduledExecutorService並添加方法“scheduleWithFixedDelayNTimes”。 也許這樣的課程已經存在? 目前,我正在使用Executors.newSingleThreadScheduledExecutor();
獲取我的ScheduledExecutorService實例。 我可能必須實現類似的功能來實例化擴展的ScheduledExecutorService。 這可能很棘手。 你怎么看待這件事?
我無法使用調度程序。 我可以改為:
for(int i = 0; i < numTimesToRun; i++){
doSomething();
Thread.sleep(delay);
}
並在某個線程中運行它。 你對那個怎么想的? 您可能仍然可以使用runnable並直接調用run方法。
歡迎任何建議。 我正在尋找辯論,找到實現目標的“最佳實踐”方式。
您可以在Future上使用cancel()方法。 來自scheduleAtFixedRate的javadoc
Otherwise, the task will only terminate via cancellation or termination of the executor
下面是一些示例代碼,它將Runnable包裝在另一個中,跟蹤原始運行的次數,並在運行N次后取消。
public void runNTimes(Runnable task, int maxRunCount, long period, TimeUnit unit, ScheduledExecutorService executor) {
new FixedExecutionRunnable(task, maxRunCount).runNTimes(executor, period, unit);
}
class FixedExecutionRunnable implements Runnable {
private final AtomicInteger runCount = new AtomicInteger();
private final Runnable delegate;
private volatile ScheduledFuture<?> self;
private final int maxRunCount;
public FixedExecutionRunnable(Runnable delegate, int maxRunCount) {
this.delegate = delegate;
this.maxRunCount = maxRunCount;
}
@Override
public void run() {
delegate.run();
if(runCount.incrementAndGet() == maxRunCount) {
boolean interrupted = false;
try {
while(self == null) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
interrupted = true;
}
}
self.cancel(false);
} finally {
if(interrupted) {
Thread.currentThread().interrupt();
}
}
}
}
public void runNTimes(ScheduledExecutorService executor, long period, TimeUnit unit) {
self = executor.scheduleAtFixedRate(this, 0, period, unit);
}
}
引用API描述( ScheduledExecutorService.scheduleWithFixedDelay
):
創建並執行一個周期性動作,該動作在給定的初始延遲之后首先被啟用,並且隨后在一次執行的終止和下一次執行的開始之間給定延遲。 如果任務的任何執行遇到異常,則后續執行被禁止。 否則,任務將僅通過取消或終止執行者來終止。
所以,最簡單的事情是“只是拋出異常” (即使這被認為是不好的做法):
static class MyTask implements Runnable {
private int runs = 0;
@Override
public void run() {
System.out.println(runs);
if (++runs >= 20)
throw new RuntimeException();
}
}
public static void main(String[] args) {
ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
s.scheduleWithFixedDelay(new MyTask(), 0, 100, TimeUnit.MILLISECONDS);
}
到目前為止, sbridges解決方案似乎是最干凈的解決方案,除了你提到的,它還有責任處理Runnable
本身的執行次數。 它不應該與此有關,而是重復應該是處理調度的類的參數。 為實現這一點,我建議使用以下設計,為Runnables
引入一個新的執行器類。 該類提供了兩種用於調度任務的公共方法,它們是標准的Runnables
,具有有限或無限重復。 如果需要,可以傳遞相同的Runnable
用於有限和無限調度(這對於擴展Runnable
類以提供有限重復的所有提議的解決方案是不可能的)。 取消有限重復的處理完全封裝在調度程序類中:
class MaxNScheduler
{
public enum ScheduleType
{
FixedRate, FixedDelay
}
private ScheduledExecutorService executorService =
Executors.newSingleThreadScheduledExecutor();
public ScheduledFuture<?> scheduleInfinitely(Runnable task, ScheduleType type,
long initialDelay, long period, TimeUnit unit)
{
return scheduleNTimes(task, -1, type, initialDelay, period, unit);
}
/** schedule with count repetitions */
public ScheduledFuture<?> scheduleNTimes(Runnable task, int repetitions,
ScheduleType type, long initialDelay, long period, TimeUnit unit)
{
RunnableWrapper wrapper = new RunnableWrapper(task, repetitions);
ScheduledFuture<?> future;
if(type == ScheduleType.FixedDelay)
future = executorService.scheduleWithFixedDelay(wrapper,
initialDelay, period, TimeUnit.MILLISECONDS);
else
future = executorService.scheduleAtFixedRate(wrapper,
initialDelay, period, TimeUnit.MILLISECONDS);
synchronized(wrapper)
{
wrapper.self = future;
wrapper.notify(); // notify wrapper that it nows about it's future (pun intended)
}
return future;
}
private static class RunnableWrapper implements Runnable
{
private final Runnable realRunnable;
private int repetitions = -1;
ScheduledFuture<?> self = null;
RunnableWrapper(Runnable realRunnable, int repetitions)
{
this.realRunnable = realRunnable;
this.repetitions = repetitions;
}
private boolean isInfinite() { return repetitions < 0; }
private boolean isFinished() { return repetitions == 0; }
@Override
public void run()
{
if(!isFinished()) // guard for calls to run when it should be cancelled already
{
realRunnable.run();
if(!isInfinite())
{
repetitions--;
if(isFinished())
{
synchronized(this) // need to wait until self is actually set
{
if(self == null)
{
try { wait(); } catch(Exception e) { /* should not happen... */ }
}
self.cancel(false); // cancel gracefully (not throwing InterruptedException)
}
}
}
}
}
}
}
為了公平起見,管理重復的邏輯仍然是一個 Runnable
,但it'a一個Runnable
完全內部的MaxNScheduler
,而Runnable
通過調度任務必須不與調度的本質關注自身。 如果需要,通過每次執行RunnableWrapper.run
時提供一些回調,這個問題也可以很容易地移出到調度程序中。 這會使代碼稍微復雜化,並且需要保留一些RunnableWrapper
的映射以及相應的重復,這就是我選擇將計數器保留在RunnableWrapper
類中的原因。
設置self時,我還在包裝器上添加了一些同步。 理論上需要這樣做,當執行結束時,可能還沒有分配自我(一個相當理論的場景,但只能重復一次)。
正確處理取消,不會拋出InterruptedException
,如果在執行取消之前調度另一輪, RunnableWrapper
將不會調用底層的Runnable
。
對於像輪詢到某個超時之類的用例,我們可以使用Future.get()
來使用更簡單的解決方案。
/* Define task */
public class Poll implements Runnable {
@Override
public void run() {
// Polling logic
}
}
/* Create executor service */
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
/* Schedule task - poll every 500ms */
ScheduledFuture<?> future = executorService.scheduleAtFixedRate(new Poll(), 0, 500, TimeUnit.MILLISECONDS);
/* Wait till 60 sec timeout */
try {
future.get(60, TimeUnit.SECONDS);
} catch (TimeoutException e) {
scheduledFuture.cancel(false);
// Take action on timeout
}
你的第一種方法似乎沒問題 您可以通過將mode
對象傳遞給它的構造函數來組合兩種類型的runnable(或者將-1作為必須運行的最大次數傳遞-1),並使用此模式來確定是否必須取消runnable:
private class DoSomethingNTimesTask implements Runnable{
private int count = 0;
private final int limit;
/**
* Constructor for no limit
*/
private DoSomethingNTimesTask() {
this(-1);
}
/**
* Constructor allowing to set a limit
* @param limit the limit (negative number for no limit)
*/
private DoSomethingNTimesTask(int limit) {
this.limit = limit;
}
@Override
public void run(){
doSomething();
count++;
if(limit >= 0 && count > limit){
// Cancel the scheduling
}
}
}
您必須將預定的未來傳遞給您的任務才能使其自行取消,否則您可能會拋出異常。
這是我的建議(我認為它處理了問題中提到的所有案例):
public class RepeatedScheduled implements Runnable {
private int repeatCounter = -1;
private boolean infinite;
private ScheduledExecutorService ses;
private long initialDelay;
private long delay;
private TimeUnit unit;
private final Runnable command;
private Future<?> control;
public RepeatedScheduled(ScheduledExecutorService ses, Runnable command,
long initialDelay, long delay, TimeUnit unit) {
this.ses = ses;
this.initialDelay = initialDelay;
this.delay = delay;
this.unit = unit;
this.command = command;
this.infinite = true;
}
public RepeatedScheduled(ScheduledExecutorService ses, Runnable command,
long initialDelay, long delay, TimeUnit unit, int maxExecutions) {
this(ses, command, initialDelay, delay, unit);
this.repeatCounter = maxExecutions;
this.infinite = false;
}
public Future<?> submit() {
// We submit this, not the received command
this.control = this.ses.scheduleWithFixedDelay(this,
this.initialDelay, this.delay, this.unit);
return this.control;
}
@Override
public synchronized void run() {
if ( !this.infinite ) {
if ( this.repeatCounter > 0 ) {
this.command.run();
this.repeatCounter--;
} else {
this.control.cancel(false);
}
} else {
this.command.run();
}
}
}
此外,它允許外部方停止來自submit()
方法返回的Future
所有內容。
用法:
Runnable MyRunnable = ...;
// Repeat 20 times
RepeatedScheduled rs = new RepeatedScheduled(
MySes, MyRunnable, 33, 44, TimeUnit.SECONDS, 20);
Future<?> MyControl = rs.submit();
...
我一直在尋找完全相同的功能,並選擇了org.springframework.scheduling.Trigger
。
下面是完整測試工作示例(如果代碼中存在太多洪水,則抱歉)applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context/ http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util/ http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<bean id="blockingTasksScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
<property name="poolSize" value="10" />
</bean>
<task:scheduler id="deftaskScheduler" pool-size="10" />
</beans>
JAVA
package com.alz.springTests.schedulerTest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
public class ScheduledTest {
private static ApplicationContext applicationContext;
private static TaskScheduler taskScheduler;
private static final class SelfCancelableTask implements Runnable, Trigger {
Date creationTime = new Date();
AtomicInteger counter = new AtomicInteger(0);
private volatile boolean shouldStop = false;
private int repeatInterval = 3; //seconds
@Override
public void run() {
log("task: run started");
// simulate "doing job" started
int sleepTimeMs = ThreadLocalRandom.current().nextInt(500, 2000+1);
log("will sleep " + sleepTimeMs + " ms");
try {
Thread.sleep(sleepTimeMs);
} catch (InterruptedException e) {
e.printStackTrace();
}
// "doing job" finished
int i = counter.incrementAndGet();
if (i > 5) { //cancel myself
logErr("Attempts exceeded, will mark as shouldStop");
shouldStop = true;
} else {
log("task: executing cycle #"+i);
}
}
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
log("nextExecutionTime: triggerContext.lastActualExecutionTime() " + triggerContext.lastActualExecutionTime());
log("nextExecutionTime: triggerContext.lastCompletionTime() " + triggerContext.lastCompletionTime());
log("nextExecutionTime: triggerContext.lastScheduledExecutionTime() " + triggerContext.lastScheduledExecutionTime());
if (shouldStop)
return null;
if (triggerContext.lastCompletionTime() == null) {
LocalDateTime ldt = creationTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().plus(repeatInterval, ChronoUnit.SECONDS);
return Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
} else {
LocalDateTime ldt = triggerContext.lastCompletionTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().plus(repeatInterval, ChronoUnit.SECONDS);
return Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
}
}
}
private static void log(String log) {
System.out.printf("%s [%s] %s\r\n", LocalDateTime.now(), Thread.currentThread(), log);
}
private static void logErr(String log) {
System.err.printf("%s [%s] %s\r\n", LocalDateTime.now(), Thread.currentThread(), log);
}
public static void main(String[] args) {
log("main: Stated...");
applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
taskScheduler = (TaskScheduler) applicationContext.getBean("blockingTasksScheduler");
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = ((ThreadPoolTaskScheduler)taskScheduler).getScheduledThreadPoolExecutor();
SelfCancelableTask selfCancelableTask = new SelfCancelableTask();
taskScheduler.schedule(selfCancelableTask, selfCancelableTask);
int waitAttempts = 0;
while (waitAttempts < 30) {
log("scheduledPool pending tasks: " + scheduledThreadPoolExecutor.getQueue().size());
try {
Thread.sleep(1*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
waitAttempts++;
}
log("main: Done!");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.