Thursday 28 November 2013

JobCron/Scheduler

Job cron or scheduler is a way or method by which we can execute a specific class with precise interval of time continuously. This concept is similar to the interrupt of microcontroller.

Procedure to achieve to JobCron :

Step1) Configure liferay-portlet.xml file by adding following code.
This can be achieve by using two different way

Method1:
<scheduler-entry>
    <scheduler-description>description</scheduler-description>
          <scheduler-event-listener-class>com.test.cron.CronJob</scheduler-event-listener-class>
             <trigger>
        <cron>
                <cron-trigger-value>0 0/1 * 1/1 * ? *</cron-trigger-value>               
                  </cron>
             </trigger>
</scheduler-entry>

com.test.cron.CronJob is complete path of class CronJob. So we can say that CronJob is a class created by the programmer which is present in package com.test.cron.
Value present in <cron-trigger-value>0 0/1 * 1/1 * ? *</cron-trigger-value> ,  means   “0 0/1 * 1/1 * ? * we get from http://www.cronmaker.com/  this site. Here we have to set the time and that site will gives this peculiar type of value. Our class executes continuously  after the given duration of time.



Method2:   

<scheduler-entry>
    <scheduler-description>description</scheduler-description>
          <scheduler-event-listener-class>com.test.cron.CronJob</scheduler-event-listener-class>
             <trigger>
        <simple>
                   <simple-trigger-value>1</simple-trigger-value>
                   <time-unit>minute</time-unit>
               </simple>
             </trigger>
</scheduler-entry>

    In this method we don’t have to worry about any site we just put the value inside the tag <simple-trigger-value>for number<simple-trigger-value/> and  <time-unit>unit time e.g. second, minute or hour</time-unit>  and our JobCron class will execute after each provided intervall of time.


CronJob.java

package com.test.cron;

import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;
import com.liferay.util.bridges.mvc.MVCPortlet;

public class CronJob extends MVCPortlet implements MessageListener
{
  
   @Override
   public void receive(Message arg0) throws MessageListenerException
   {
       // Inside this method whatever code we write will execute continuously with provided specific interval of time
       System.out.println("This output is printed because of job cron or scheduler");

   }
}

   receive method will call automatically means in this class receive method is entry point of execution. So even if we want to write other method inside this class we have to call those from receive method. Here receive method behaves as main function in Language C.

No comments:

Post a Comment