Day 7 : Cron Jobs in Hybris
One of the most common questions asked in interviews.
Scheduled processes are extremely important in any complex system. Hybris also provides an efficient solution for making such tasks easy.

There are three crucial components for scheduling a task in Hybris. They are
- Trigger— It is just for scheduling purpose. We can define the schedule using a cron expression.
INSERT_UPDATE Trigger; cronjob(code)[unique = true] ; cronExpression
; exampleCronJob; 0 0 12 ? * SAT *
2. CronJob — We can extend the Cronjob itemtype and define any extra parameters needed for our task. If no inputs need t be configured, we are free to use the CronJob item type itself to configure our task.
Below code is used whenever we are extending the CronJob
<itemtype code="ExampleCronJob" autocreate="true" generate="true" extends="CronJob">
<attributes>
<attribute qualifier="dateFrom" type="java.util.Date">
<modifiers read="true" write="true" optional="true"/>
<persistence type="property"/>
</attribute>
</attributes>
</itemtype>INSERT_UPDATE ExampleCronJob; code[unique = true] ; job(code) ; sessionLanguage(isocode)
; exampleCronJob; exampleJob; en
Suppose if you do not have any input parameters, there is no need to extend the Cron Job item and you can define your cron job just through the impex.
INSERT_UPDATE CronJob; code[unique = true] ; job(code) ; sessionLanguage(isocode)
; exampleCronJob; exampleJob; en
3. Job — Next comes the crucial part. This contains the logic part of our task.
I see that we can extend the JobModel for this. But I have always followed the service layer job to define the logic. The other solution through extending JobModel is no longer used by anyone I believe.
INSERT_UPDATE ServicelayerJob; code[unique = true] ; springId
; exampleJob; exampleJob
Here exampleJob should be defined as a spring bean which extends the AbstractjobPerformable. Override abortable method in case you want the job to be aborted in between processing.
public class ExampleJob extends AbstractJobPerformable<CronJobModel> {
@Override
public PerformResult perform(CronJobModel cronJobModel) {
//logic here}}@Override
public boolean isAbortable() {
return true;
}
Defining Bean
<bean id="exampleJob" class="com.sap.core.jobs.cronJob.ExampleJob"
parent="abstractJobPerformable">
<property name="abortable" value="true"/>//only if it needs to be abortable
</bean>
For making a job, either we can override the isAbortable method or we can define it through spring config. One thing to remember when adding abortable is to frequently call clearAbortRequestedIfNeeded in your perform method to see if any abort request is received. Otherwise there is no point in making the job abortable.
if(clearAbortRequestedIfNeeded(cronJob))
{
//abort the job
//do some clean-up
return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED);
}