KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Situation I have a Runnable. I have a class that schedules this Runnable for execution using a ScheduledExecutorService with scheduleWithFixedDelay . Goal I want to alter this class to schedule the Runnable for fixed delay execution either indefinitely, or until it has been run a certain number of times, depending on some parameter that is passed in to the constructor. If possible, I would like to use the same Runnable, as it is conceptually the same thing that should be "run". Possible approaches Approach #1 Have two Runnables, one that cancels the schedule after a number of executions (which it keeps a count of) and one that doesn't: 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 Fu
Tags (comma-separated)
Save Edits
Cancel