def METHOD_NAME(hosts, destination, log_data, timeout=None, inventory_id=None):
    log_data['inventory_id'] = inventory_id
    log_data['written_ct'] = 0
    try:
        os.makedirs(destination, mode=0o700)
    except FileExistsError:
        pass
    if timeout is None:
        timeout = settings.ANSIBLE_FACT_CACHE_TIMEOUT
    if isinstance(hosts, QuerySet):
        hosts = hosts.iterator()
    last_filepath_written = None
    for host in hosts:
        if (not host.ansible_facts_modified) or (timeout and host.ansible_facts_modified < now() - datetime.timedelta(seconds=timeout)):
            continue  # facts are expired - do not write them
        filepath = os.sep.join(map(str, [destination, host.name]))
        if not os.path.realpath(filepath).startswith(destination):
            system_tracking_logger.error('facts for host {} could not be cached'.format(smart_str(host.name)))
            continue
        try:
            with codecs.open(filepath, 'w', encoding='utf-8') as f:
                os.chmod(f.name, 0o600)
                json.dump(host.ansible_facts, f)
                log_data['written_ct'] += 1
                last_filepath_written = filepath
        except IOError:
            system_tracking_logger.error('facts for host {} could not be cached'.format(smart_str(host.name)))
            continue
    # make note of the time we wrote the last file so we can check if any file changed later
    if last_filepath_written:
        return os.path.getmtime(last_filepath_written)
    return None