diff --git a/Civi/Api4/Action/ContactCategory/Sync.php b/Civi/Api4/Action/ContactCategory/Sync.php index a7dde97..77bcd01 100644 --- a/Civi/Api4/Action/ContactCategory/Sync.php +++ b/Civi/Api4/Action/ContactCategory/Sync.php @@ -17,18 +17,27 @@ use CRM_Core_DAO; */ class Sync extends \Civi\Api4\Generic\AbstractAction { + /** + * Usually this will not act unless the time is right. + * + * @default FALSE + * @var bool + */ + protected $force = FALSE; + public function _run(Result $result) { ini_set('memory_limit', '256M'); Civi::log()->debug('Begin', ['=start' => 'ContactCatSync', '=timed' => 1]); - $settings = Civi::settings()->get('contact_categories'); + // this does not unserialize $settings = Civi::settings()->get('contact_categories'); $settings = Setting::get(FALSE) ->addSelect('contact_categories') ->execute()->first()['value'] ?? NULL; if (empty($settings['groupIDs'])) { throw new \API_Exception('Unconfigured'); } - if ($settings['updateAfter'] > time()) { + if (!$this->force && time() < $settings['updateAfter']) { // not needed yet. + Civi::log()->debug("Skipping because not due until " . date('H:i j M Y', $settings['updateAfter']), ['=' => 'pop']); return; } @@ -49,7 +58,7 @@ class Sync extends \Civi\Api4\Generic\AbstractAction { } } if ($smartGroups) { - Civi::log()->debug('Refreshing smart groups', ['=' => 'timed', 'groups' => $smartGroups]); + Civi::log()->debug('Refreshing smart groups', ['=' => 'timed,start', 'groups' => $smartGroups]); \CRM_Contact_BAO_GroupContactCache::loadAll($smartGroups); Civi::log()->debug('', ['=' => 'pop']); } @@ -150,8 +159,16 @@ class Sync extends \Civi\Api4\Generic\AbstractAction { $summary['changes'] = $n; $_ = memory_get_peak_usage(TRUE); $summary['memory_use'] = @round($_ / pow(1024, ($i = floor(log($_, 1024)))), 2) . ' ' . ['b', 'kb', 'mb', 'gb', 'tb', 'pb'][$i]; - Civi::log()->debug('Complete.', ['=' => 'set']); $result->exchangeArray($summary); + + // Limit to running every 6 hours. + $settings['updateAfter'] = time() + 60 * 60 * 6; + Setting::set(FALSE) + ->addValue('contact_categories', $settings) + ->execute(); + + Civi::log()->debug("Complete. Scheduling next run after " . date('H:i j M Y', $settings['updateAfter']), ['=' => 'set']); + } }