Hello,
Few weeks ago I asked for help with my problem. My problem was mainly occurred because of the way I was running a task periodically.
I was running the task likes this:
ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(1,Thread.ofVirtual().factory());
threadPoolExecutor.execute(this::task());
public void task(){
long startTime = System.currentTimeMillis();
try{
//some code
}catch(Exception ignored){
}finally{
long endTime = System.currentTimeMillis();
//start a new task every 1000ms.
//startIn = 1000ms - execution_time
//if the startIn is negative. start the task immediately.
long startIn = 1000 - (endTime - startTime);
threadPoolExecutor.schedule(
this::task, //runnable implementation
startIn,
TimeUnit.MILLISECONDS
);
}
}
The idea of my scheduling is to start a new task every 1000ms.
To do this, I take in consideration the execution time and I calculate the remained time. But, if the remained time is negative, start the next task immediately.
This code initially worked. But after a while, it suddenly stopped (without any error) and not schedule anymore.
I am asking for your help to find a good solution for this case.
I also don't want the tasks to be queued, like with scheduleAtFixedRate(). Because there is some case where I end up with multiple tasks in queue, and then all these tasks are executed one after another (e.g. 3 tasks in less than 1000ms).
I also don't like scheduleWithFixedDelay because is not taking in consideration the execution time, and I run the next tasks later than I want.
Continuation in comments