Automating Report Generation in Bitrix: Agents and Cron Setup
The Problem with Manual Report Exports
A manager spends 1–2 hours every morning: log into the admin panel, select dates, download Excel, email it. Mistakes happen—wrong columns, forgot to attach. For an urgent request for last month's report, they dig through all documentation. This is typical for dozens of companies on Bitrix. Lost time: 40 hours per month, costing roughly $2,000 at $50/hour. Automating report generation solves the problem in a day of development—and saves 90% of that cost, equating to over $24,000 annually. This article covers automated report generation in Bitrix, including cron setup and agent configuration for reports. But without experience, common pitfalls occur: cron not configured, write permissions on /upload/reports not set, agents not logging errors. Our certified Bitrix engineers with 10+ years of experience guarantee stable agent operation in production.
Why Automation Outperforms Manual Work
Manual export requires human involvement. An automated agent runs at 3 a.m., with no server load. Time savings exceed 90%, and the automation is 240 times faster than manual. Compare:
| Parameter | Manual Export | Automated Generation |
|---|---|---|
| Time for 5 reports | 30 minutes | 0 minutes |
| Errors | possible | eliminated |
| Regularity | on request | scheduled |
| Annual cost savings | baseline | up to 90% reduction (~$24,000/year) |
Automation cuts overhead by over 90% while eliminating human error.
How We Configure Agents and Cron
Setting Up Cron and Creating an Agent
On a production server, you must use system cron instead of an HTTP trigger. Add the job to crontab:
# /etc/cron.d/bitrix */5 * * * * www-data /usr/bin/php /var/www/site/bitrix/modules/main/include/cron_events.php > /dev/null 2>&1 Without cron, agents run only on site visits, which is unreliable.
Example agent code (expand)
Agents in Bitrix are PHP functions executed on schedule via CAgent. Example of creating an agent:
\CAgent::AddAgent( 'GenerateDailyReports();', 'local', 'N', 86400, '', 'Y', date('d.m.Y H:i:s', mktime(8, 0, 0)), 30 ); Bitrix Documentation
Agent Template and Email Sending
function GenerateDailyReports(): string { $reports = [ [ 'type' => 'orders', 'filename' => 'orders_' . date('Y-m-d') . '.xlsx', 'params' => ['date_from' => date('Y-m-d', strtotime('-1 day')), 'status' => null], 'recipient' => '[email protected]', ], [ 'type' => 'low_stock', 'filename' => 'stock_' . date('Y-m-d') . '.xlsx', 'params' => ['threshold' => 5], 'recipient' => '[email protected]', ], ]; foreach ($reports as $reportConfig) { try { $generator = ReportGeneratorFactory::create($reportConfig['type']); $filePath = $generator->generate($reportConfig['params']); $savedName = '/upload/reports/' . $reportConfig['filename']; rename($filePath, $_SERVER['DOCUMENT_ROOT'] . $savedName); sendReportEmail($reportConfig['recipient'], $savedName, $reportConfig['filename']); \Bitrix\Main\Diag\Debug::writeToFile( date('Y-m-d H:i:s') . ' Report generated: ' . $reportConfig['filename'], '', '/local/logs/reports.log' ); } catch (\Throwable $e) { \Bitrix\Main\Diag\Debug::writeToFile( date('Y-m-d H:i:s') . ' ERROR: ' . $e->getMessage(), '', '/local/logs/reports_errors.log' ); } } return 'GenerateDailyReports();'; } Email Delivery
The report is sent via Bitrix mail event or directly through PHPMailer with an attachment.
function sendReportEmail(string $to, string $filePath, string $fileName): void { $absolutePath = $_SERVER['DOCUMENT_ROOT'] . $filePath; $mail = new \PHPMailer\PHPMailer\PHPMailer(true); $mail->CharSet = 'UTF-8'; $mail->setFrom('[email protected]', 'Report System'); $mail->addAddress($to); $mail->Subject = 'Auto-report: ' . $fileName . ' from ' . date('d.m.Y'); $mail->Body = 'The report was generated automatically. File attached.'; $mail->addAttachment($absolutePath, $fileName); $mail->send(); } Storage and Archive Cleanup
Generated files are stored in /upload/reports/ with a 30-day history. Cleanup of old files is a separate agent:
function CleanOldReports(): string { $dir = $_SERVER['DOCUMENT_ROOT'] . '/upload/reports/'; foreach (glob($dir . '*.xlsx') as $file) { if (filemtime($file) < time() - 30 * 86400) { unlink($file); } } return 'CleanOldReports();'; } Archive page in the manager's personal cabinet—list of files with date and download link, with permission checks.
Which Reports to Automate?
Any report that can be built via Bitrix ORM or infoblocks. We frequently automate:
- Daily/weekly/monthly sales (grouped by managers)
- Warehouse stock with threshold alerts
- Orders in "pending payment" status
- Competitor price dynamics (if scraping is in place)
- Reconciliation statements with contractors
Each report type gets its own class implementing ReportGeneratorInterface. This allows adding new reports without changing the core. In practice, one factory can serve 20 different reports: configuration is an array, logic is in separate methods. For large datasets, we use chunked queries (500 records per chunk) and streaming write to XLSX via PhpSpreadsheet Writer to avoid memory overflow with 100,000 rows.
Security Against Unauthorized Access
Store files in /upload/reports/ with permission checks via $USER. Configure .htaccess to deny direct web access. The download link must be generated via a script with rights verification. Log all downloads to a separate file.
Typical Mistakes and Recommendations
- Agents run only on site hits—solve with cron.
- Incorrect permissions on
/upload/reports—write access for www-data. - Code errors without logging—enable
Debug::writeToFile. - Execution timeout—for large reports use
set_time_limit(0).
What's Included in the Work
- Project analysis: identify needed reports and their parameters.
- Cron setup and agent creation per report.
- Development of report templates (Excel/PDF/CSV) with required data.
- Email delivery setup with attachment.
- Error logging and successful generation registration.
- Automatic cleanup of old files (configurable retention period).
- Documentation of the scheme and manager training.
Timeline Estimates
| Configuration | Timeframe | Cost |
|---|---|---|
| 1 agent + 1 report type + email | from 1 day | from $500 |
| 3–5 reports with different schedules | 2–4 days | from $1,500 |
| Report archive + UI in personal cabinet + notifications | 4–6 days | from $3,000 |
Timelines are approximate; final estimates are given after analyzing your project. Contact us to get an engineer consultation and cost estimate for your project. Order automated report generation setup—free managers from routine and errors. Our certified Bitrix specialists guarantee stable operation and error-free delivery.

