ScheduledExecutorService可在本地和测试服务器中使用,但只能在实时服务器中运行一次

时间:2018-11-21 16:49:49

标签: java scheduling runnable executorservice scheduledexecutorservice

我有一个ScheduledExecutorService来安排任务在tomcat应用程序中每12小时运行一次。该任务将调用REST端点并执行其他一些计算并返回结果。它在本地和测试服务器中都可以正常工作,但是,它只能在实时服务器中运行一次,而不会再运行。所有异常均得到处理,任务完成时间不到5秒。我还检查了服务器中的所有属性,以确保时间属性不会被其他属性覆盖。为了进行本地测试,我将延迟时间减少到每10分钟一次,但这仍然显示出相同的行为,因此我将超时视为问题。我看过其他类似的问题,但似乎都没有帮助。 ScheduledExecutorService only runs onceJAVA ScheduledExecutorService only runs once when calling a Task<V>ScheduledExecutorService only loops onceScheduledExecutorService - Task stops runningScheduledExecutorService - Ignore already running runnableScheduledExecutorService schedule issueTimer vs. ScheduledExecutorService scheduling

下面是我的代码:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({"name", "number"})
public class Company {

    @JsonProperty("name")
    private String name;
    @JsonProperty("number")
    private int number;

    public String getName() {
        return this.name;
    }

    public int getNumber() {
        return this.number;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(Company.class)
            .append("name", this.name)
            .append("number", this.number).toString();
    }
}

public class CompanyDifference {

    private String name;
    private int difference;

    public CompanyDifference(String name, int difference) {
        this.name = name;
        this.difference = difference;
    }

    public String getName() {
        return this.name;
    }

    public int getDifference() {
        return this.difference;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(CompanyDifference.class)
            .append("name", this.name)
            .append("difference", this.difference).toString();
    }
}

@Singleton
public class TaskRunner {
    public void doTask () {
        try {
            System.out.println("takes 2 sets of json data and returns the difference for each company");

            // takes 2 sets of json data and returns the difference for each company
            ObjectMapper mapper = new ObjectMapper();
            InputStream dataOne = Company.class.getResourceAsStream("/data.json");
            InputStream dataTwo = Company.class.getResourceAsStream("/data2.json");

            Company[] companyDataOne = mapper.readValue(dataOne, Company[].class);
            Company[] companyDataTwo = mapper.readValue(dataTwo, Company[].class);

            // Find the difference for each company and map company name to difference
            Map<String, Integer> mapDifferenceToCompany = new HashMap<>();

            for (int i = 0; i < companyDataOne.length; i++) {
                mapDifferenceToCompany.put(companyDataOne[i].getName(), Math.abs(companyDataOne[i].getNumber() - companyDataTwo[i].getNumber()));
            }

            mapDifferenceToCompany.forEach((key, value) -> System.out.println(String.valueOf(new CompanyDifference(key, value))));
        } catch (IOException e) {
            logger.info(String.format("Error: Failed to convert json to object with exception %s", e));
            throw new TaskSchedulerException("Failed to convert json to object with exception", e);
        } catch (Exception e) {
            logger.info(String.format("Error: Failed with exception %s", e));
            throw new TaskSchedulerException("Failed with exception", e);
        }
    }
}

@Singleton
public class TaskScheduler {

    private final Runnable runnable; 
    private final ScheduledExecutorService executorService;
    private static final Logger logger = LoggerFactory.getLogger(TaskScheduler.class);

    @Inject
    public TaskScheduler(TaskRunner taskRunner, int initialDelay, int period, String timeUnits) {
        this.executorService = Executors.newScheduledThreadPool(1);
        this.runnable = taskRunner::doTask;

        this.scheduledFuture = this.executorService.scheduleAtFixedRate(this.runnable, initialDelay, period,    
             TimeUnit.valueOf(timeUnits));
    }

    public static void main(String[] args) {
        TaskRunner taskRunner = new TaskRunner();
        new TaskScheduler(taskRunner, 1, 10, "MINUTES");
    }
}

任务在初始延迟1分钟后启动时会运行一次,但不会运行下一个计划任务。它尝试运行计划的任务,但似乎没有完成任务,在检查实时服务器中的ScheduledThreadPoolExecutor属性后,我发现队列大小降至0(应始终为1),这意味着没有任务预定的。

这表明在初始任务完成后尝试运行计划任务时,它会删除计划任务,或者由于当前任务尚未完成而无法计划下一个任务。由于在doTask方法中已处理所有异常,因此不会引发任何错误或异常。调度程序可以在本地和测试服务器中按预期方式工作,这使得复制方案非常困难。

想要了解实现是否缺少某些内容或可能导致其无法完成下一个计划任务的原因以及使队列大小降至0的原因。java版本是否会对调度程序的行为产生影响?在现场环境中为什么会发生这种情况?

我创建了一个REST端点,以使用ScheduledFuture和ScheduledThreadPoolExecutor的属性来监视引擎内部发生的事情

ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) schedulerService;
this.queueSize = executor.getQueue().size();
this.remainingCapacity = executor.getQueue().remainingCapacity();
this.terminated = schedulerService.isTerminated();
this.shutdown = schedulerService.isShutdown();
this.taskCount = executor.getTaskCount();
this.activeTaskCount = executor.getActiveCount();
this.completedTaskCount = executor.getCompletedTaskCount();
this.keepAliveTime = executor.getKeepAliveTime(TimeUnit.SECONDS);
this.coreThreadTimeOut = executor.allowsCoreThreadTimeOut();
this.cancelled = scheduledFuture.isCancelled();
this.delay = scheduledFuture.getDelay(TimeUnit.MINUTES);

经过最初的延迟后第一次运行的结果:从这里,我们可以看到它完成了第一个任务,并且我确实从计算中获得了所需的结果。 taskCount(自启动以来已调度的任务数)为2,表示已调度第二个任务,队列大小仍为1,可以。

{
  "queueSize": 1,
  "remainingCapacity": 2147483647,
  "terminated": false,
  "shutdown": false,
  "taskCount": 2,
  "activeTaskCount": 0,
  "completedTaskCount": 1,
  "keepAliveTime": 0,
  "coreThreadTimeOut": false, 
  "periodic": true, 
  "cancelled": false
}

尝试第二次运行后的结果:这是卡住的地方。 completedTaskCount为2,但我认为它实际上并未完成任务,因为我没有从计算或任何日志中得到结果来表明它已经开始或完成了任务。 taskCount应该增加到3,但是卡在2中,并且队列大小现在为0。

{
  "queueSize": 0,
  "remainingCapacity": 2147483647,
  "terminated": false,
  "shutdown": false,
  "taskCount": 2,
  "activeTaskCount": 0,
  "completedTaskCount": 2,
  "keepAliveTime": 0,
  "coreThreadTimeOut": false, 
  "periodic": true, 
  "cancelled": false
}

当我在本地和测试服务器上检查它们时,它可以正常工作,并且taskCount按预期增长,并且队列大小始终为1,这是预期的。由此可见,由于某种原因,该任务在第二次运行时被卡住,无法完成,因此无法安排下一个任务。

javadoc说:“如果此任务的任何执行花费的时间超过其周期,那么后续执行可能会延迟启动,但不会同时执行。” 我假设这就是下一个原因任务未安排。如果您能解释什么可能导致这种情况发生,那就太好了

1 个答案:

答案 0 :(得分:0)

问题未随执行,执行就可以了。经过大量调试后,运行该应用程序的VM盒似乎出现了故障。多次重新启动并重新部署应用程序服务后,它又恢复了正常。 请参阅问题以了解调试应用程序时采取的步骤。