I have a(or many) cron task, and it executed every 5s(this is not matter), and i want it will not execute if the previous running is unfinished. Here is my code: and if the scheduler execute first time at 12:00:00, I want it executed after 12:00:10 for the second(third ...) times. Can anyone help me ?
public class Task {
private Long id;
private String cron;
private Long millis; //the task runnig time(begin to end)
//getter setter
}
public class TaskSchedulerTest {
private Map<Long, ScheduledFuture> futureMap = new HashMap<>();
public static void main(String[] args) {
new TaskSchedulerTest().t();
}
private void t() {
Task t1 = new Task(1L, "0/3 * * * * *", 10000L);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
taskScheduler.setThreadNamePrefix("scheduler task");
ScheduledFuture sf1 = taskScheduler.schedule(new RunnableTask(t1), new CronTrigger(t1.getCron()));
futureMap.put(t1.getId(), sf1);
}
private class RunnableTask implements Runnable {
private Task task;
private int times;
private RunnableTask() {
}
private void println(String string) {
System.out.println(Thread.currentThread().getName() + string);
}
private RunnableTask(Task task) {
this.task = task;
}
@Override
public void run() {
//check if previous is not finished, i checked it's isDone()
//and it return false while the previous is running
println(" begin: " + task.getId() + " times: " + times);
ScheduledFuture future = futureMap.get(task.getId());
println(" done: " + future.isDone());
try {
Thread.sleep(task.getMillis()); //or do something
} catch (InterruptedException e) {
e.printStackTrace();
}
println(" end: " + task.getId() + " times: " + times);
times++;
}
}
}
I use new cron "0/3 * * * * *" and replace sleep to read and write file, like this:
FileInputStream fis = new FileInputStream("D:\\test\\test.exe");
FileOutputStream fos = new FileOutputStream("D:\\test\\a-" + times + "");
fos.write(IOUtils.toByteArray(fis));
fos.flush();
fos.close();
fis.close();
And this is the log:
scheduler task1 begin: 1 times: 0 timestamp:05:51
scheduler task1 end: 1 times: 0 timestamp:06:10
scheduler task1 begin: 1 times: 1 timestamp:06:11
scheduler task1 end: 1 times: 1 timestamp:06:17
scheduler task2 begin: 1 times: 2 timestamp:06:18
scheduler task2 end: 1 times: 2 timestamp:06:24
scheduler task1 begin: 1 times: 3 timestamp:06:25
scheduler task1 end: 1 times: 3 timestamp:06:33
scheduler task3 begin: 1 times: 4 timestamp:06:34
scheduler task3 end: 1 times: 4 timestamp:06:40
The log mean my problem is not a problem.