Note: This is toy code and not production ready.
I want to schedule MyTask
to run every fixed delay (say 2 seconds for example). And this task when done wants itself to be stopped. The code for MyTask
is:
public class MyTask implements Runnable {
MainClass parent;
AtomicInteger integer = new AtomicInteger(0);
public MyTask(MainClass parent) {
this.parent = parent;
}
@Override
public void run() {
try {
int valueNow = integer.incrementAndGet();
System.out.println("Running with value: " + valueNow + " and going to do work");
Thread.sleep((long)(Math.random() * 10000)); // simulate some work
System.out.println("Running with value: " + valueNow + " and work over");
if(valueNow == 5) {
parent.stopTask();
}
} catch (Exception exception) {
System.out.println("Interrupted");
}
}
}
And the MainClass
is the one which schedules it:
public class MainClass {
private ScheduledExecutorService executorService;
private ScheduledFuture updateFuture;
public static void main(String[] args) {
new MainClass().startMyTask();
}
public void startMyTask() {
System.out.println("Starting MyTask to run every 2 seconds..............");
executorService = Executors.newScheduledThreadPool(2);
updateFuture = executorService.scheduleAtFixedRate(new MyTask(this), 1, 2, TimeUnit.SECONDS);
}
public void stopTask() {
System.out.println("Stopping MyTask to run further");
updateFuture.cancel(true);
}
}
This is just a toy code to reproduce the scenario. Is there anything wrong with this approach where I am passing a reference to the parent to the thread so that it can be stopped? Is there any better approach for this?