Writing a cronjob script
This page is for application creators who write the code a cronjob part runs. New scripts are classes extending
Exponential\Runnable\CronjobPart, with a one-line entry file; the plain-file form of older scripts still works
(A cronjob part).
Contents
The class and the entry file
// extension/expdemo/classes/runnable/cronjobs/expdemoimport.php
namespace Exponential\Cronjob\Extension\Expdemo;
class ExpdemoImport extends \Exponential\Runnable\CronjobPart
{
public function run( array $scope )
{
$cli = $scope['cli'];
$result = \expDemoImportService::importNewItems( 100 ); // the work lives in a service class
if ( empty( $scope['isQuiet'] ) )
$cli->output( "Imported {$result['created']} items, updated {$result['updated']}" );
}
}
/**
* @description Import new items from the partner feed
*/
// extension/expdemo/cronjobs/expdemo_import.php
return \Exponential\Cronjob\Extension\Expdemo\ExpdemoImport::main( __FILE__, get_defined_vars() );Regenerate the autoloads, add the script to a part (Cronjobs for applications) and run
it with php runcronjobs.php -s <siteaccess> --script=expdemo_import.php.
What the script receives
get_defined_vars() passes what eZRunCronjobs::runScript() defines: $cli (an eZCLI for output) and $isQuiet.
The kernel is initialized for the siteaccess given with -s; the current user is anonymous.
Output
- One line per meaningful result; no output in quiet mode except errors.
$cli->error( ... )for errors, so they stand out in logs.- The
@descriptiontag is whatphp bin/php/console list cronand Setup > Cronjobs show (Describe your own script).
Doing the work well
| Rule | Why |
|---|---|
| Work in batches with a limit per run | a run must end before the next one starts |
| Make it idempotent (remote IDs, "processed" markers) | a crashed run is simply repeated |
| Log in a dedicated user when you write content | permissions and the audit name a real account, not the administrator |
| Catch errors per item, continue, report at the end | one bad record should not stop the rest |
| Clear in-memory caches between batches | long runs otherwise run out of memory |
| Hand slow single tasks to a queue | the part stays short (Queues with expqueue) |
Testing
Keep the logic in a service class and test it with PHPUnit; run the script by hand with --script on a development
copy; check the output in Setup > Cronjobs (Testing applications).
Related pages
- Cronjobs for applications
- CLI scripts with eZScript
- Cronjob cookbook (
doc/eng-us/examples/cookbook/cronjob.md) - Free documentation: this page is free to copy, translate and improve under the GNU FDL 1.3.
Become an Exponential Partner
Partners share their information, provide funding, contribute back and develop the products with us, and that is how Exponential grows. A partner website and dashboard are planned for mid-2027: please become a partner today to speed up our growth rate and land new features faster.