Liferay 7.3 scheduler Entry

 A scheduler serves to perform background tasks at certain defined intervals.

StorageType Information

we should first discuss the supported StorageTypes. Liferay has three supported StorageTypes:

StorageType.MEMORY_CLUSTERED - This is the default storage type . This storage type combines two aspects, MEMORY and CLUSTERED.

For MEMORY, Its not persisted in DB , but stored in Memory . For CLUSTERED, the job is cluster-aware meaning that  at any point of time job will run in only one node in the cluster.

StorageType.MEMORY - No job information is persisted. The important part here is that you may miss some job runs in cases of outages.  And unlike in PERSISTED, when the server comes up the job will not run even though it was missed. Note that this storage type is not cluster-aware, so your job will run on every node in the cluster which could cause duplicate runs.

StorageType.PERSISTED -Job details will be persisted in the database. If there is an outage and job did not trigger , when the server comes up  it will realize the job was missed and will immediately process the job.

In clustered environment we must prefer either  MEMORY_CLUSTERED or PERSISTED to ensure your job doesn't run on every node . 

Below are the steps to create cron/scheduler in liferay 7.3 

Step -1  )  Create a component which extends  BaseMessageListener 

//code snippet

@Component(

immediate = true,property = {"cron.expression=0 0 0 * * ?"},

service = CustomCronScheduler.class )

public class CustomCronScheduler extends BaseMessageListener { 

................

}

 Step -2  )  Set the storageType

protected StorageType getStorageType() {

    if (_schedulerEntryImpl instanceof StorageTypeAware) {

      return ((StorageTypeAware) _schedulerEntryImpl).getStorageType();

    }     

    return StorageType.PERSISTED;

  }

Step-3  Activate the component 

protected void activate(Map<String,Object> properties ) {

String cronExpression = GetterUtil.getString(properties.get("cron.expression"), _DEFAULT_CRON_EXPRESSION);

    Class<?> clazz = getClass();

String className = clazz.getName();

Trigger trigger = _triggerFactory.createTrigger(className, className, new Date(), null, cronExpression);

SchedulerEntry schedulerEntry = new SchedulerEntryImpl(className, trigger);

_schedulerEngineHelper.register(this, schedulerEntry, DestinationNames.SCHEDULER_DISPATCH);

}

Step -4 Deactivate the component

@Deactivate

  protected void deactivate() {

    if (_initialized) {

      try {

        _schedulerEngineHelper.unschedule(_schedulerEntryImpl, getStorageType());

      } catch (SchedulerException se) {

        if (_log.isWarnEnabled()) {

          _log.warn("Unable to unschedule trigger", se);

        }

      }

      _schedulerEngineHelper.unregister(this);

    }

    _initialized = false;

  }


Complete code is available at git location. 






Comments

Popular posts from this blog

MVC Action Command