Creating a Background Task

The com.psddev.dari.util.Task class is the base task class. It contains basic execution control and status methods. For example, you can schedule start times, run one time or repeatedly with periodic delays, pause and resume execution, and display status.

You can create a background task by extending the abstract Task class. Using a subclass or anonymous class, implement your task logic in the Task#doTask method. For example, in the following code snippet for an anonymous class, a new task called “Migration Task” is created, appearing in the “Migration” category of the Task Status tool. For each execution of the doTask method, the system increments the task’s run count by one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
...

public MigrationTask() {
   task.submit(); // Run task one time
}

Task task = new Task("Migration", "Migration Task") {
   @Override
   public void doTask() throws Exception {
     boolean done = false;
     while(!done && shouldContinue()) {
         // do processing here
     }
   }
};

In the previous snippet—

  • Lines 3–5 are the constructor, where the submit method is called. This method starts the task immediately and runs it one time.
  • Lines 7–15 are the anonymous class that implements the doTask method. It is a best practice to call shouldContinue on each iteration of the loop to determine if the task has been stopped or paused in the Task Status tool.

Note that as an alternative to the submit method, you can schedule a task to run repeatedly in periodic intervals.