How to schedule a task dynamically in spring java

Viewed 2154

I want to schedule a task dynamiclly for example i have task A, B, C. I want to execute task 'A' at 9 am, task 'B' at 12.30 pm and task 'C' at 7 pm. But i dont want to repeat the task on same time every day. I want to set task schedule dynamiclly . I have Googled a lot and i found only static task scheduling procedure. In spring java i got only fixed and cron expression like this @Scheduled(cron = "0 15 10 15 * ?") which is totally static , for cron expression you can just run a task on a fixed time of a day. So please help me.

1 Answers

I think you're looking for this (from official documentation):

The Spring TaskScheduler Abstraction

In addition to the TaskExecutor abstraction, Spring 3.0 introduced a TaskScheduler with a variety of methods for scheduling tasks to run at some point in the future. The following listing shows the TaskScheduler interface definition:

public interface TaskScheduler {

    ScheduledFuture schedule(Runnable task, Trigger trigger);

    ScheduledFuture schedule(Runnable task, Instant startTime);

    ScheduledFuture schedule(Runnable task, Date startTime);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Instant startTime, Duration period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Duration period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Duration delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);
}

TaskScheduler can schedule a task at a specifed Date or Instant:

ScheduledFuture schedule(Runnable task, Instant startTime);

ScheduledFuture schedule(Runnable task, Date startTime);

So you should be able to do:

scheduler.schedule(task, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format("2018-11-07 17:46:00"));
Related