Call a method on a specific dates using ThreadPoolTaskExecutor

vphilipnyc

I have a method that I wish to run once using Spring and it needs to run on a given java.util.Date (or LocalDateTime alternatively). I am planning to persist all of the dates that the method should execute to a data source. It should run asynchronously.

One way is to check the DB every day for a date and execute the method if the date has passed and hasn't been executed. Is there a better way?

I know that Spring offers a ThreadPoolTaskScheduler and a ThreadPoolTaskExecutor. I am looking at ScheduledFuture schedule(Runnable task, Date startTime) from the TaskScheduler interface. Would I need to create a Runnable Spring managed bean just to call my method? Or is there a simpler annotation that would do this? An example would really help.

(Looked here too.)

Ian Mc

By externalizing the scheduled date (to a database), the typical scheduling practices (i.e. cron based, or fixed scheduling) no longer apply. Given a target Date, you can schedule the task accurately as follows:

Date now = new Date();
Date next = ... get next date from external source ...
long delay = next.getTime() - now.getTime();
scheduler.schedule(Runnable task, delay, TimeUnit.MILLISECONDS);

What remains is to create an efficient approach to dispatching each new task. The following has a TaskDispatcher thread, which schedules each Task based on the next java.util.Date (which you read from a database). There is no need to check daily; this approach is flexible enough to work with any scheduling scenario stored in the database.

To follow is working code to illustrate the approach.

The example Task used; in this case just sleeps for a fixed time. When the task is complete, the TaskDispatcher is signaled through a CountDownLatch.

public class Task implements Runnable {

    private final CountDownLatch completion;
    public Task(CountDownLatch completion) {
        this.completion = completion;
    }

    @Override
    public void run() {
        System.out.println("Doing task");
        try {
            Thread.sleep(60*1000);  // Simulate the job taking 60 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        completion.countDown();     // Signal that the job is complete
    }

}

The dispatcher is responsible for reading the database for the next scheduled Date, launching a ScheduledFuture runnable, and waiting for the task to complete.

public class TaskDispatcher implements Runnable {

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private boolean isInterrupted = false;

    @Override
    public void run() {

        while (!isInterrupted) {

            Date now = new Date();

            System.out.println("Reading database for next date");
            Date next = ... read next data from database ...

            //Date next = new Date();   // Used as test
            //next.setTime(now.getTime()+10*1000); // Used as test

            long delay = next.getTime() - now.getTime();
            System.out.println("Scheduling next task with delay="+delay);

            CountDownLatch latch = new CountDownLatch(1);
            ScheduledFuture<?> countdown = scheduler.schedule(new Task(latch), delay, TimeUnit.MILLISECONDS);

            try {
                System.out.println("Blocking until the current job has completed");
                latch.await();
            } catch (InterruptedException e) {
                System.out.println("Thread has been requested to stop");
                isInterrupted = true;
            }
            if (!isInterrupted)
                System.out.println("Job has completed normally");
        }

        scheduler.shutdown();

    }

}

The TaskDispatcher was started as follows (using Spring Boot) - start the thread as you normally do with Spring:

@Bean
public TaskExecutor taskExecutor() {
    return new SimpleAsyncTaskExecutor(); // Or use another one of your liking
}

@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
    return new CommandLineRunner() {
        public void run(String... args) throws Exception {
            executor.execute(new TaskDispatcher());
        }
    };
}

Let me know if this approach will work for your use case.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Call a method on a specific dates using ThreadPoolTaskExecutor

分類Dev

how can I redraw a circle on an HTML5 canvas in this specific case? (method call versus directly using context object)

分類Dev

Filter Dates Between Two Specific Dates In an Excel Column using C# Interop

分類Dev

How to call a method of another class using codemodel

分類Dev

Call method from sibling component using ReactJS

分類Dev

Can we call method using the reference of the class

分類Dev

Unload NPAPI plugin using script method call

分類Dev

Forward call on a functional interface using method handles

分類Dev

React. How to call method of specific subchild in component tree

分類Dev

WPF: How to call a method at a specific point in time while an animation is running

分類Dev

Grouping using multiple columns, then summing a specific column using method syntax

分類Dev

How to Pass Data in ajax call using GET Method in javascript

分類Dev

Using stream to call class method and collect results in a list

分類Dev

How can I call `didSet` method using `Codable` protocol

分類Dev

How to call a Rust struct's method from C using FFI?

分類Dev

Call Rest ful service using HttpWebRequest and PUT Method

分類Dev

How to call method at App start if I am using provider?

分類Dev

CALL METHOD and method chaining

分類Dev

Return specific dates, months from any year using python date time

分類Dev

Using Dates in an MVC application

分類Dev

Adding a method call to a collection

分類Dev

Call back method between

分類Dev

Call Method with parameters in AppDelegate

分類Dev

Asynchronous Method Call In PHP

分類Dev

Android - Delay method call

分類Dev

Call method ViewDidload Swift

分類Dev

Split data frame by a set of specific dates

分類Dev

Dates from the last month of specific ranges

分類Dev

Mysql count and group between specific dates

Related 関連記事

  1. 1

    Call a method on a specific dates using ThreadPoolTaskExecutor

  2. 2

    how can I redraw a circle on an HTML5 canvas in this specific case? (method call versus directly using context object)

  3. 3

    Filter Dates Between Two Specific Dates In an Excel Column using C# Interop

  4. 4

    How to call a method of another class using codemodel

  5. 5

    Call method from sibling component using ReactJS

  6. 6

    Can we call method using the reference of the class

  7. 7

    Unload NPAPI plugin using script method call

  8. 8

    Forward call on a functional interface using method handles

  9. 9

    React. How to call method of specific subchild in component tree

  10. 10

    WPF: How to call a method at a specific point in time while an animation is running

  11. 11

    Grouping using multiple columns, then summing a specific column using method syntax

  12. 12

    How to Pass Data in ajax call using GET Method in javascript

  13. 13

    Using stream to call class method and collect results in a list

  14. 14

    How can I call `didSet` method using `Codable` protocol

  15. 15

    How to call a Rust struct's method from C using FFI?

  16. 16

    Call Rest ful service using HttpWebRequest and PUT Method

  17. 17

    How to call method at App start if I am using provider?

  18. 18

    CALL METHOD and method chaining

  19. 19

    Return specific dates, months from any year using python date time

  20. 20

    Using Dates in an MVC application

  21. 21

    Adding a method call to a collection

  22. 22

    Call back method between

  23. 23

    Call Method with parameters in AppDelegate

  24. 24

    Asynchronous Method Call In PHP

  25. 25

    Android - Delay method call

  26. 26

    Call method ViewDidload Swift

  27. 27

    Split data frame by a set of specific dates

  28. 28

    Dates from the last month of specific ranges

  29. 29

    Mysql count and group between specific dates

ホットタグ

アーカイブ