How is task planning implemented?

I did a piece of work to extract some data from the web service, but now I am having a problem with the query schedule and I'm not sure where to start.

I listen to the jms queue for events and after receiving the event I need to make a request to the web service after the duration. Duration varies depending on the attributes of the event. If the web service returns false, I need to continue scheduling requests until it returns true.

I was thinking about creating a request for viewing in the queue when I receive either an event or a false response, but this does not seem ideal - I would constantly consume messages, checking the time to see if the request should be made again and return it to the queue, if not.

If anyone got any tips on how to implement such a problem, I would really appreciate it.

+3
source share
4 answers

I decided to go with Spring Task Scheduling , which was introduced in version 3. It offers integration, scheduling based on both time points and intervals, and if additional configuration is required, it has the cron option. I did not delve into the depths of what can be achieved with quartz, but it also offers integration with this.

0
source

-, , , . , , . PriorityQueue .

. , . Object.wait(long) , , .

, . , , . Object.notifyAll() , . , , , .

public class ProcessingQueue extends Thread {

  private PriorityQueue<Task> tasks;  

  private volatile boolean isRunning = true;

  public void addTask(Task t) {
    synchronized (this.tasks) {
      this.tasks.offer(t);
      // this call requires synchronization to this.tasks
      this.tasks.notifyAll();
    }
  }

  public void shutdown() {
    this.isRunning = false;
    synchronized (this.tasks) {
      this.notifyAll();
    }
  }

  public void run() {
    while (this.isRunning) {
      synchronized (this.tasks) {
        Task t = this.tasks.peek();
        // by default, if there are no tasks, this will wake every 60 seconds
        long millisToSleep = 60000;
        // getExecuteMillis() should return the time, in milliseconds, for execution
        if (t != null) millisToSleep = t.getExecuteMillis() - System.currentTimeMillis();
        if (millisToSleep > 0) {
          try {
            // this line requires synchronization to this.tasks
            // and the lock is removed while it waits
            this.tasks.wait(millisToSleep);
          } catch (InterruptedException e) {
          }
        }
        t = this.tasks.poll();
        if (t != null) {
          t.execute();
        }
      }
    }
  }
}
+6

Use existing OSS scheduler: http://java-source.net/open-source/job-scheduler

You can always order your own, but I would not recommend it.

One important feature of the scheduler should be that it survives a reboot / crash.

+2
source

Source: https://habr.com/ru/post/1776442/


All Articles