Featured post

Docker setup for Liferay 7 with MySQL

Thursday, 3 May 2018

Background Task Liferay 7 or DXP Part 1

Executing or scheduling background task is always an important activity for developers.

There are so many scenarios where background tasks are used like import/export, sending bulk notification or email, processing orders etc.

You can find this interesting link here which talks in length for background tasks.
What it does not offer is implementation example and changes for background task in Liferay 7/DXP

By following few Liferay conventions, we can easily use this weapon.
In this example I will explain creation of background task, pass parameters and handle errors if any.

In next example I will demonstrate check status, progress and display it over UI.

We will be creating two osgi components for this activity.
1. Create osgi module for background task creation and register it to handler
2. Use above module to create background tasks

Render method to create background task every time portlet loads.

@Overridepublic void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
    Random random = new Random(12);

    HttpServletRequest request = PortalUtil

    ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest

    ServiceContext serviceContext = null;
    try {
        serviceContext = ServiceContextFactory.getInstance(renderRequest);
    } catch (PortalException e) {
        logger.error("Eror in getting service context", e.getCause());

    // This taskContextMap can be used as transporter to background job
    Map taskContextMap = new HashMap<>();
    taskContextMap.put("processName", "testing " + random.nextInt());
    taskContextMap.put("totalNodes", String.valueOf(random.nextInt()));
    //taskContextMap.put("serviceContext", serviceContext);    try {
        // Adding the job to liferay background manager
        com.liferay.portal.kernel.backgroundtask.BackgroundTask backgroundTask = backgroundTaskmanager.addBackgroundTask(themeDisplay.getUserId(),
                themeDisplay.getScopeGroupId(), SampleBackgroundTaskExecutor.class.getName(),SampleBackgroundTaskExecutor.class.getName(),taskContextMap, serviceContext);
        // With returned background object you can check status, id etc.

    } catch (PortalException e) {
    } catch (SystemException e) {

Create Background Task Executor

        immediate = true,
        property = {"background.task.executor.class.name=com.netcracker.cabinet.background.executor.MigrationBackgroundTaskExecutor"}, 
        // Without this property osgi will not register this as background executor/handler
        service = BackgroundTaskExecutor.class)
public class SampleBackgroundTaskExecutor extends BaseBackgroundTaskExecutor {

isSerial - True

// if it's not serial then multiple instances of this executor can run parallel, to run it in queue mode, we use isSerial true
@Overridepublic boolean isSerial() {
    return true;

Main execute method for the Job

public BackgroundTaskResult execute(BackgroundTask backgroundTask)
      throws Exception {
      // taskContextMap which is sent by the caller
      Map taskContextMap = backgroundTask.getTaskContextMap();

      String taskName = (String)taskContextMap.get("processName") ;
      String totalNodes = (String)taskContextMap.get("totalNodes");

      //ServiceContext serviceContext  = (ServiceContext) taskContextMap.get("serviceContext");
      LOGGER.debug("Task Name : "+ taskName);

   BackgroundTaskVO messageContent = new BackgroundTaskVO();

   // Sending the data to util for MessageBus

  // Telling the system if, background task is successful or not
   BackgroundTaskResult backgroundTaskResult = new BackgroundTaskResult(
   backgroundTaskResult.setStatusMessage("Wonder full");
   return backgroundTaskResult;

Message Bus update

public static void sendStatusMessage(BackgroundTaskVO messageContent) {
   // Leave if no background task
   if (!BackgroundTaskThreadLocal.hasBackgroundTask()) {

   // Message Creation
   Message message = createMessage(messageContent);

   // Send message to message bus

You can download the source code from here

You are just done, Try & Enjoy the function.............:)


  1. AWS Training in Bangalore - Live Online & Classroom
    myTectra Amazon Web Services (AWS) certification training helps you to gain real time hands on experience on AWS. myTectra offers AWS training in Bangalore using classroom and AWS Online Training globally. AWS Training at myTectra delivered by the experienced professional who has atleast 4 years of relavent AWS experince and overall 8-15 years of IT experience. myTectra Offers AWS Training since 2013 and retained the positions of Top AWS Training Company in Bangalore and India.

    IOT Training in Bangalore - Live Online & Classroom
    IOT Training course observes iot as the platform for networking of different devices on the internet and their inter related communication. Reading data through the sensors and processing it with applications sitting in the cloud and thereafter passing the processed data to generate different kind of output is the motive of the complete curricula. Students are made to understand the type of input devices and communications among the devices in a wireless media.

  2. Hi Buddy Nice article !! Just a question where at which point you are adding the real task like importing a file or anything else in this code ?

  3. Thanks for your great and helpful presentation I like your good service. I always appreciate your post. That is very interesting I love reading and I am always searching for informative information like this.AngularJS Training in Chennai | Best AngularJS Training Institute in Chennai

  4. Wow!! Really a nice Article. Thank you so much for your efforts. Definitely, it will be helpful for others. I would like to follow your blog. Share more like this. Thanks Again.
    iot training in Chennai | Best iot Training Institute in Chennai

  5. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.

    machine learning course in Chennai
    machine learning training center in Chennai
    machine learning certification in chennai
    Android training in chennai
    PMP training in chennai

  6. I want to tell you how cool I spend my free time on this site is just super genteelonline slot games A bunch of slots and slot machines. Many people can even meet someone and of course have fun

  7. Great Post,really it was very helpful for us.
    Thanks a lot for sharing!
    I found this blog to be very useful!!
    JAVA training in Bangalore

  8. Nice information thank you,if you want more information please visit our link machine learning online course

  9. Yet, then again, these progressions will significantly affect everybody all over the place. In both individual and expert lives. machine learning course in pune