public static function cleanup() {
        global $CFG, $DB;

        // Delete logs older than the retention period.
        $params = [
            'retentionperiod' => time() - $CFG->task_logretention,
        ];
        $logids = $DB->get_fieldset_select('task_log', 'id', 'timestart < :retentionperiod', $params);
        self::delete_task_logs($logids);

        // Delete logs to retain a minimum number of logs.
        $sql = "SELECT classname FROM {task_log} GROUP BY classname HAVING COUNT(classname) > :retaincount";
        $params = [
            'retaincount' => $CFG->task_logretainruns,
        ];
        $classes = $DB->get_fieldset_sql($sql, $params);

        foreach ($classes as $classname) {
            $notinsql = "";
            $params = [
                'classname' => $classname,
            ];

            $retaincount = (int) $CFG->task_logretainruns;
            if ($retaincount) {
                $keeplogs = $DB->get_records('task_log', [
                        'classname' => $classname,
                    ], 'timestart DESC', 'id', 0, $retaincount);

                if ($keeplogs) {
                    list($notinsql, $params) = $DB->get_in_or_equal(array_keys($keeplogs), SQL_PARAMS_NAMED, 'p', false);
                    $params['classname'] = $classname;
                    $notinsql = " AND id {$notinsql}";
                }
            }

            $logids = $DB->get_fieldset_select('task_log', 'id', "classname = :classname {$notinsql}", $params);
            self::delete_task_logs($logids);
        }
    }