简体   繁体   中英

schedule on task at a time - java

I have a task that is scheduled periodically. Sometime it can take longer than expected. I am trying to find a way to make sure that scheduling will be canceled in case the task is already running. All mechanisms I check will make the task wait and run it after the first finish

locking ofcourse will do the job but I'm looking of something more high level

Any Idea

You can use ScheduledExecutorService . scheduleAtFixedRate is probably what you want as it will wait for your tasks to finish, iff one takes longer than the rate you specify:

If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

Example:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

scheduler.scheduleAtFixedRate(() -> {
    // Body will be executed every second unless the previous task hasn't finished.
}, 0L, 1L, TimeUnit.SECONDS);

There is something called scheduleAtFixedRate and scheduleAtFixedDelay.

scheduleAtFixedRate will start another process at defined time, so if previous process is not completed, two processes will be running and it might cause race condition of running same thing twice.

scheduleAtFixedDelay will start after fixed time once a task is completed.

scheduleAtFixedRate vs scheduleWithFixedDelay

In Spring you can do this by using annotation:-

@Scheduled(fixedDelay =30000)

http://howtodoinjava.com/spring/spring-core/4-ways-to-schedule-tasks-in-spring-3-scheduled-example/

do you know Apache Camel framework? It has a module called quartz2 and has a much possibility to scheduling any task.

try read this page: http://camel.apache.org/quartz2.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM