Java: Scheduled Tasks

柔情痞子 提交于 2019-12-22 00:53:57

问题


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.


回答1:


Here's one way:

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);
        }
    }
}


来源:https://stackoverflow.com/questions/7775622/java-scheduled-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!