I need to create a thread that runs infinitely as a stand alone process withing Spring MVC controller.
The thread will start when the controller is hit for the first time. I don't want to reschedule every time controller is hit.
@RequestMapping(method = RequestMethod.GET)
public String runTask() {
//I want this to be scheduled first time controller is hit but
//I don't want it to rechadule every time it is hit again
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// do stuff
}
}, 0, 5, TimeUnit.SECONDS);
return "Task was scheduled to run";
}
Is there a better way to do this?