阻止cron执行,如果它已经在运行

时间:2018-05-19 16:45:00

标签: java cron scheduler

我有一个(或许多)cron任务,它每5秒执行一次(这没关系),我希望如果先前的运行未完成,它将不会执行。 这是我的代码:如果调度程序在12:00:00执行第一次,我希望它在12:00:10之后执行第二次(第三次......)次。任何人都可以帮助我吗?

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++;
        }
    }
}

我使用新的cron“0/3 * * * * *”并将sleep替换为读写文件,如下所示:

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();

这是日志:

  

scheduler task1 begin:1次:0时间戳:05:51

     

scheduler task1 end:1次:0时间戳:06:10

     

scheduler task1 begin:1次:1个时间戳:06:11

     

scheduler task1 end:1次:1个时间戳:06:17

     

调度程序任务2开始:1次:2时间戳:06:18

     

scheduler task2 end:1次:2 timestamp:06:24

     

scheduler task1 begin:1次:3 timestamp:06:25

     

scheduler task1 end:1次:3 timestamp:06:33

     

scheduler task3 begin:1次:4 timestamp:06:34

     

scheduler task3 end:1次:4 timestamp:06:40

日志意味着我的问题不是问题。

0 个答案:

没有答案