#!/usr/bin/env python3
import trough
from trough.settings import settings
import logging
import time

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='Run a "server" sync process, which controls other sync processes, ' \
        'or a "local" sync process, which loads segments onto the current machine and performs health checks.')

    parser.add_argument('--server', dest='server', action='store_true',
                        help='run in server mode: control the actions of other local synchronizers.')
    args = parser.parse_args()

    controller = trough.sync.get_controller(args.server)
    controller.check_config()
    while True:
        controller.sync()
        logging.info('Sleeping for %s seconds' % settings['SYNC_LOOP_TIMING'])
        time.sleep(settings['SYNC_LOOP_TIMING'])
@@ -93,16 +93,32 @@
 ort time
+%0Aimport datetime
 %0A%0Aif __n
@@ -712,103 +712,206 @@
     
-controller.sync()%0A        logging.info('Sleeping for %25s seconds' %25 settings%5B'SYNC_LOOP_TIMING'%5D
+started = datetime.datetime.now()%0A        controller.sync()%0A        loop_duration = datetime.datetime.now() - started%0A        sleep_time = settings%5B'SYNC_LOOP_TIMING'%5D - loop_duration.total_seconds(
 )%0A  
@@ -920,44 +920,151 @@
     
+sleep_
 time
-.
+ = 
 sleep
-(settings%5B'SYNC_LOOP_TIMING'%5D
+_time if sleep_time %3E 0 else 0%0A        logging.info('Sleeping for %25s seconds' %25 round(sleep_time))%0A        time.sleep(sleep_time
 )

fix sync loop timing, lower copying time limit to 50% of TTL, measure sync timing and don't sleep if we are over SYNC_LOOP_TIMING already.