Java:计划任务 [英] Java: Scheduled Tasks

查看:128
本文介绍了Java:计划任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个任务-任务A和任务B.任务A应该首先执行,并且在完成后,我要启动我的定期任务B,该任务一直在执行,直到成功为止. 我如何在Java中实现呢?我当时在看排定的执行服务,但这些服务似乎更多地基于时间,而不是任务状态.

I have 2 tasks - Task A and Task B. Task A should execute first and on completion, I want to start my periodic Task B which keeps doing a task until it becomes success. How can I implement this in java? I was looking at scheduled execution services but those seem to be more time based rather than state of a task.

推荐答案

这是一种方法:

import java.util.concurrent.*;

public class ScheduledTasks {
    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
        FollowupTask followupTask = new FollowupTask(executorService);
        FirstTask firstTask = new FirstTask(followupTask, executorService);
        executorService.submit(firstTask);
    }

    static class FirstTask implements Runnable {
        private FollowupTask followup;
        private ScheduledExecutorService executorService;

        FirstTask(FollowupTask followup, ScheduledExecutorService executorService) {
            this.followup = followup;
            this.executorService = executorService;
        }

        @Override
        public void run() {
            System.out.println("First task: counting to 5");
            for (int i = 1; i <= 5; i++) {
                sleep(1000);
                System.out.println(i);
            }
            System.out.println("All done! Submitting followup task.");
            executorService.submit(followup);
        }
    }

    static class FollowupTask implements Runnable {
        private int invocationCount = 0;
        private ScheduledExecutorService executorService;

        public FollowupTask(ScheduledExecutorService executorService) {
            this.executorService = executorService;
        }

        @Override
        public void run() {
            invocationCount++;
            if (invocationCount == 1) {
                System.out.println("Followup task: resubmit while invocationCount < 20");
            }
            System.out.println("invocationCount = " + invocationCount);
            if (invocationCount < 20) {
                executorService.schedule(this, 250, TimeUnit.MILLISECONDS);
            } else {
                executorService.shutdown();
            }
        }
    }

    static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new IllegalStateException("I shouldn't be interrupted!", e);
        }
    }
}

这篇关于Java:计划任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆