EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
Scheduled Jobs populator
Yurii70b4a3ad245d
diff --git a/application/Espo/Classes/ConsoleCommands/PopulateScheduledJobs.php b/application/Espo/Classes/ConsoleCommands/PopulateScheduledJobs.phpnew file mode 100644index 0000000000..864fd3bd54--- /dev/null+++ b/application/Espo/Classes/ConsoleCommands/PopulateScheduledJobs.php@@ -0,0 +1,62 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Classes\ConsoleCommands;++use Espo\Core\Console\Command;+use Espo\Core\Console\Command\Params;+use Espo\Core\Console\IO;+use Espo\Core\Utils\ScheduledJob\Populator;++/**+ * @noinspection PhpUnused+ */+class PopulateScheduledJobs implements Command+{+ public function __construct(+ private Populator $populator,+ ) {}++ public function run(Params $params, IO $io): void+ {+ $names = $this->populator->populate();++ if ($names === []) {+ $io->writeLine("Nothing to create.");++ return;+ }++ $io->writeLine("Created scheduled jobs:");++ foreach ($names as $name) {+ $io->writeLine(' ' . $name);+ }+ }+}diff --git a/application/Espo/Core/Utils/ScheduledJob/Populator.php b/application/Espo/Core/Utils/ScheduledJob/Populator.phpnew file mode 100644index 0000000000..5faded12d0--- /dev/null+++ b/application/Espo/Core/Utils/ScheduledJob/Populator.php@@ -0,0 +1,108 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\Core\Utils\ScheduledJob;++use Espo\Core\Utils\Language;+use Espo\Core\Utils\Metadata;+use Espo\Entities\ScheduledJob;+use Espo\ORM\EntityManager;++/**+ * @internal+ * @since 10.0.0+ */+class Populator+{+ public function __construct(+ private EntityManager $entityManager,+ private Metadata $metadata,+ private Language $defaultLanguage,+ ) {}++ /**+ * @return string[]+ */+ public function populate(): array+ {+ $output = [];++ /** @var array<string, array{isDefault?: bool, scheduling?: string}> $defs */+ $defs = $this->metadata->get('app.scheduledJobs', []);++ foreach ($defs as $name => $def) {+ $scheduling = $def['scheduling'] ?? null;+ $idDefault = $def['isDefault'] ?? false;++ if (!$idDefault || !$scheduling) {+ continue;+ }++ $created = $this->createIsNotExists($name, $scheduling);++ if ($created) {+ $output[] = $name;+ }+ }++ return $output;+ }++ private function createIsNotExists(string $name, string $scheduling): bool+ {+ if ($this->exists($name)) {+ return false;+ }++ $recordName = $this->defaultLanguage->translateOption($name, 'job', ScheduledJob::ENTITY_TYPE);++ $entity = $this->entityManager->getRDBRepositoryByClass(ScheduledJob::class)->getNew();++ $entity+ ->setJob($name)+ ->setActive()+ ->setScheduling($scheduling)+ ->setName($recordName);++ $this->entityManager->saveEntity($entity);++ return true;+ }++ private function exists(string $name): bool+ {+ $one = $this->entityManager->getRDBRepositoryByClass(ScheduledJob::class)+ ->where([+ ScheduledJob::FIELD_JOB => $name,+ ])+ ->findOne();++ return $one !== null;+ }+}diff --git a/application/Espo/Entities/ScheduledJob.php b/application/Espo/Entities/ScheduledJob.phpindex 75498e3d7f..ffd55c1d9e 100644--- a/application/Espo/Entities/ScheduledJob.php+++ b/application/Espo/Entities/ScheduledJob.php@@ -34,9 +34,14 @@ use Espo\Core\ORM\Entity;class ScheduledJob extends Entity{- public const ENTITY_TYPE = 'ScheduledJob';+ public const string ENTITY_TYPE = 'ScheduledJob';- public const STATUS_ACTIVE = 'Active';+ public const string STATUS_ACTIVE = 'Active';++ /**+ * @since 10.0.0+ */+ public const string FIELD_JOB = 'job';public function getName(): ?string{@@ -50,6 +55,38 @@ class ScheduledJob extends Entitypublic function getJob(): ?string{- return $this->get('job');+ return $this->get(self::FIELD_JOB);+ }++ /**+ * @since 10.0.0+ */+ public function setActive(): self+ {+ return $this->set('status', self::STATUS_ACTIVE);+ }++ /**+ * @since 10.0.0+ */+ public function setName(string $name): self+ {+ return $this->set(Field::NAME, $name);+ }++ /**+ * @since 10.0.0+ */+ public function setScheduling(string $scheduling): self+ {+ return $this->set('scheduling', $scheduling);+ }++ /**+ * @since 10.0.0+ */+ public function setJob(string $job): self+ {+ return $this->set(self::FIELD_JOB, $job);}}diff --git a/application/Espo/Modules/Crm/Resources/metadata/app/scheduledJobs.json b/application/Espo/Modules/Crm/Resources/metadata/app/scheduledJobs.jsonnew file mode 100644index 0000000000..14ea6ecda0--- /dev/null+++ b/application/Espo/Modules/Crm/Resources/metadata/app/scheduledJobs.json@@ -0,0 +1,14 @@+{+ "ControlKnowledgeBaseArticleStatus": {+ "scheduling": "10 1 * * *",+ "isDefault": true+ },+ "SendEmailReminders": {+ "scheduling": "/2 * * * *",+ "isDefault": true+ },+ "ProcessMassEmail": {+ "scheduling": "10,30,50 * * * *",+ "isDefault": true+ }+}diff --git a/application/Espo/Resources/metadata/app/consoleCommands.json b/application/Espo/Resources/metadata/app/consoleCommands.jsonindex de3526a4fa..e89648a385 100644--- a/application/Espo/Resources/metadata/app/consoleCommands.json+++ b/application/Espo/Resources/metadata/app/consoleCommands.json@@ -59,6 +59,12 @@"className": "Espo\\Classes\\ConsoleCommands\\PopulateNumbers","listed": false},+ "populateScheduledJobs": {+ "className": "Espo\\Classes\\ConsoleCommands\\PopulateScheduledJobs",+ "listed": true,+ "allowedFlags": [],+ "allowedOptions": []+ },"checkFilePermissions": {"className": "Espo\\Classes\\ConsoleCommands\\CheckFilePermissions","listed": true,diff --git a/application/Espo/Resources/metadata/app/scheduledJobs.json b/application/Espo/Resources/metadata/app/scheduledJobs.jsonindex 6185f0f811..d0f9da2fec 100644--- a/application/Espo/Resources/metadata/app/scheduledJobs.json+++ b/application/Espo/Resources/metadata/app/scheduledJobs.json@@ -48,26 +48,40 @@"isSystem": true},"Cleanup": {- "jobClassName": "Espo\\Classes\\Jobs\\Cleanup"+ "jobClassName": "Espo\\Classes\\Jobs\\Cleanup",+ "scheduling": "1 1 * * 0",+ "isDefault": true},"AuthTokenControl": {- "jobClassName": "Espo\\Classes\\Jobs\\AuthTokenControl"+ "jobClassName": "Espo\\Classes\\Jobs\\AuthTokenControl",+ "scheduling": "*/6 * * * *",+ "isDefault": true},"SendEmailNotifications": {- "jobClassName": "Espo\\Classes\\Jobs\\SendEmailNotifications"+ "jobClassName": "Espo\\Classes\\Jobs\\SendEmailNotifications",+ "scheduling": "*/2 * * * *",+ "isDefault": true},"ProcessWebhookQueue": {- "jobClassName": "Espo\\Classes\\Jobs\\ProcessWebhookQueue"+ "jobClassName": "Espo\\Classes\\Jobs\\ProcessWebhookQueue",+ "scheduling": "*/2 * * * *",+ "isDefault": true},"CheckEmailAccounts": {"preparatorClassName": "Espo\\Classes\\JobPreparators\\CheckEmailAccounts",- "jobClassName": "Espo\\Classes\\Jobs\\CheckEmailAccounts"+ "jobClassName": "Espo\\Classes\\Jobs\\CheckEmailAccounts",+ "scheduling": "*/1 * * * *",+ "isDefault": true},"CheckInboundEmails": {"preparatorClassName": "Espo\\Classes\\JobPreparators\\CheckInboundEmails",- "jobClassName": "Espo\\Classes\\Jobs\\CheckInboundEmails"+ "jobClassName": "Espo\\Classes\\Jobs\\CheckInboundEmails",+ "scheduling": "*/1 * * * *",+ "isDefault": true},"SendScheduledEmails": {- "jobClassName": "Espo\\Classes\\Jobs\\SendScheduledEmails"+ "jobClassName": "Espo\\Classes\\Jobs\\SendScheduledEmails",+ "scheduling": "*/10 * * * *",+ "isDefault": true}}diff --git a/install/core/Installer.php b/install/core/Installer.phpindex d5ac600c4d..174bfe20a7 100644--- a/install/core/Installer.php+++ b/install/core/Installer.php@@ -477,6 +477,9 @@ class Installer$this->createRecord($entityName, $data);}}++ /** @noinspection PhpInternalEntityUsedInspection */+ $this->getInjectableFactory()->create(ScheduledJobUtil\Populator::class)->populate();}private function createRecord(string $entityType, array $data): voiddiff --git a/install/core/afterInstall/records.php b/install/core/afterInstall/records.phpindex daf6280f04..c948098768 100644--- a/install/core/afterInstall/records.php+++ b/install/core/afterInstall/records.php@@ -37,66 +37,4 @@ return ['isHtml ' => '1',]],- 'ScheduledJob' => [- [- 'name' => 'Check Group Email Accounts',- 'job' => 'CheckInboundEmails',- 'status' => 'Active',- 'scheduling' => '*/2 * * * *',- ],- [- 'name' => 'Check Personal Email Accounts',- 'job' => 'CheckEmailAccounts',- 'status' => 'Active',- 'scheduling' => '*/1 * * * *',- ],- [- 'name' => 'Send Email Reminders',- 'job' => 'SendEmailReminders',- 'status' => 'Active',- 'scheduling' => '*/2 * * * *',- ],- [- 'name' => 'Send Email Notifications',- 'job' => 'SendEmailNotifications',- 'status' => 'Active',- 'scheduling' => '*/2 * * * *',- ],- [- 'name' => 'Clean-up',- 'job' => 'Cleanup',- 'status' => 'Active',- 'scheduling' => '1 1 * * 0',- ],- [- 'name' => 'Send Mass Emails',- 'job' => 'ProcessMassEmail',- 'status' => 'Active',- 'scheduling' => '10,30,50 * * * *',- ],- [- 'name' => 'Auth Token Control',- 'job' => 'AuthTokenControl',- 'status' => 'Active',- 'scheduling' => '*/6 * * * *',- ],- [- 'name' => 'Control Knowledge Base Article Status',- 'job' => 'ControlKnowledgeBaseArticleStatus',- 'status' => 'Active',- 'scheduling' => '10 1 * * *',- ],- [- 'name' => 'Process Webhook Queue',- 'job' => 'ProcessWebhookQueue',- 'status' => 'Active',- 'scheduling' => '*/2 * * * *',- ],- [- 'name' => 'Send Scheduled Emails',- 'job' => 'SendScheduledEmails',- 'status' => 'Active',- 'scheduling' => '*/10 * * * *',- ],- ],];diff --git a/schema/metadata/app/scheduledJobs.json b/schema/metadata/app/scheduledJobs.jsonindex 210e4db20f..2cd250e8ea 100644--- a/schema/metadata/app/scheduledJobs.json+++ b/schema/metadata/app/scheduledJobs.json@@ -27,6 +27,10 @@"preparatorClassName": {"type": "string","description": "A preparator. Optional. The preparator is called by the application. It serves for creating job records. E.g. for email checking, the preparator creates jobs for each email account. Should implement Espo\\Core\\Job\\Preparator."+ },+ "isDefault": {+ "type": "boolean",+ "description": "Created upon installation or when running `populate-scheduled-jobs` command. As of v10.0."}}}diff --git a/tests/integration/Espo/Core/Utils/ScheduledJob/PopulatorTest.php b/tests/integration/Espo/Core/Utils/ScheduledJob/PopulatorTest.phpnew file mode 100644index 0000000000..1b198b3f00--- /dev/null+++ b/tests/integration/Espo/Core/Utils/ScheduledJob/PopulatorTest.php@@ -0,0 +1,69 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace tests\integration\Espo\Core\Utils\ScheduledJob;++use Espo\Core\Utils\ScheduledJob\Populator;+use Espo\Entities\ScheduledJob;+use Espo\ORM\Query\DeleteBuilder;+use tests\integration\Core\BaseTestCase;++class PopulatorTest extends BaseTestCase+{+ public function testPopulate(): void+ {+ $deleteQuery = DeleteBuilder::create()+ ->from(ScheduledJob::ENTITY_TYPE)+ ->where([+ ScheduledJob::FIELD_JOB => 'Cleanup',+ ])+ ->build();++ $this->getEntityManager()->getQueryExecutor()->execute($deleteQuery);+++ $this->assertEquals(0, $this->getJobCount());++ $populator = $this->getInjectableFactory()->create(Populator::class);++ $populator->populate();++ $this->assertEquals(1, $this->getJobCount());+ }++ private function getJobCount(): int+ {+ return $this->getEntityManager()+ ->getRDBRepositoryByClass(ScheduledJob::class)+ ->where([+ ScheduledJob::FIELD_JOB => 'Cleanup',+ ])+ ->count();+ }+}