Cronjob Scripts Advanced Features

See some advanced features of cronjob scripts.

The previous example showed a simple one-line script that only printed out a message. However, it is possible to do much more, for example, you can influence the result, pass information to logs, and access the cronjob that is being executed.

Returning Cronjob Results

ScriptingJobPerformable handles returning the PerformResult(), holding the status of the cronjob, which is the final result of the cronjob perform logic.

For example, returning a String 'My script is almost finished', will only print the message out, but the final PerformResult is set "outside".

The following example shows how to influence the PerformResult.

import de.hybris.platform.servicelayer.cronjob.PerformResult
import de.hybris.platform.cronjob.enums.CronJobStatus
import de.hybris.platform.cronjob.enums.CronJobResult
println 'hello groovy! '+ new Date()
new PerformResult(CronJobResult.UNKNOWN, CronJobStatus.PAUSED)

This sets the Cronjob status to Paused. Of course, it is possible to set any kind of PerformResult, for example depending on some conditions set earlier.

Cronjob Item as Context Parameter

It is possible to access the currently executed cronjob (as a CronJobModel instance). It is passed as a context parameter ( key="cronjob").

println 'hello groovy! '+ new Date()
println cronjob.code
println cronjob.status

//etc...

Logging Inside Cronjob Scripts

The cronjob API offers many logging possibilities, including storing logs in the database.

Proper logger is available inside scripts as context parameter. You can add your own logs:

println 'hello groovy! '+ new Date()
log4j2.logger.info('my custom info log')
log4j2.logger.warn('my custom warn log')
log4j2.logger.error('my custom error log')
 
//etc...

Use the logtodatabase property to create a cronjob that will use a specific log level.

Logs outside the script (ScriptingJobPerformable), will also be considered in such case. Might be useful, if, for example, the script lookup fails. In this case, the script internal logs will not be visible, but the error log with ScriptNotFoundException will be stored.