Skip to main content
POST
/
devices
/
{device_id}
/
sync-time
curl -X POST \
  https://your-server.com/devices/principal/sync-time
{
  "success": true,
  "message": "[principal] Hora sincronizada."
}

Overview

This endpoint synchronizes the ZKTeco device’s internal clock with the server’s current time. This ensures accurate attendance timestamps and is critical for maintaining data integrity across multiple devices.

Path Parameters

device_id
string
required
The unique identifier of the device to synchronize

How It Works

  1. The server captures its current timestamp using datetime.now()
  2. A connection is established with the ZKTeco device
  3. The device’s internal clock is updated to match the server time
  4. The connection is closed
The device immediately starts using the new time for all subsequent attendance records.
curl -X POST \
  https://your-server.com/devices/principal/sync-time
{
  "success": true,
  "message": "[principal] Hora sincronizada."
}

Response Fields

success
boolean
Indicates whether the time synchronization was successful
message
string
Confirmation message with the device ID (only present on success)
error
string
Detailed error message if synchronization failed (only present when success is false)

Error Codes

  • 404: Device not found in the registry
  • 500: Connection error or device communication failure

Best Practices

Scheduled Synchronization

Implement periodic time synchronization to prevent clock drift:
import requests
import schedule
import time

def sync_all_devices():
    devices = requests.get("https://your-server.com/devices").json()
    
    for device in devices["data"]:
        device_id = device["id"]
        response = requests.post(
            f"https://your-server.com/devices/{device_id}/sync-time"
        )
        
        if response.json()["success"]:
            print(f"✓ Synced {device_id}")
        else:
            print(f"✗ Failed to sync {device_id}")

# Run every day at 3 AM
schedule.every().day.at("03:00").do(sync_all_devices)

while True:
    schedule.run_pending()
    time.sleep(60)

Check Before Sync

Verify time drift before synchronizing:
const syncIfNeeded = async (deviceId, maxDriftSeconds = 60) => {
  // Get current device time
  const timeResponse = await fetch(
    `https://your-server.com/devices/${deviceId}/time`
  );
  const timeData = await timeResponse.json();
  
  if (!timeData.success) {
    console.error(`Failed to get time for ${deviceId}`);
    return;
  }
  
  // Calculate drift
  const deviceTime = new Date(timeData.device_time);
  const serverTime = new Date();
  const driftSeconds = Math.abs((deviceTime - serverTime) / 1000);
  
  if (driftSeconds > maxDriftSeconds) {
    console.log(`Drift detected: ${driftSeconds}s. Syncing...`);
    
    const syncResponse = await fetch(
      `https://your-server.com/devices/${deviceId}/sync-time`,
      { method: 'POST' }
    );
    
    const syncData = await syncResponse.json();
    console.log(syncData.message);
  } else {
    console.log(`Device ${deviceId} time is accurate`);
  }
};

Batch Synchronization

Sync multiple devices in parallel:
import asyncio
import aiohttp

async def sync_device(session, device_id):
    url = f"https://your-server.com/devices/{device_id}/sync-time"
    async with session.post(url) as response:
        data = await response.json()
        return device_id, data["success"]

async def sync_all_devices(device_ids):
    async with aiohttp.ClientSession() as session:
        tasks = [sync_device(session, device_id) for device_id in device_ids]
        results = await asyncio.gather(*tasks)
        
        for device_id, success in results:
            status = "✓" if success else "✗"
            print(f"{status} {device_id}")

# Usage
device_ids = ["principal", "bodega", "almacen"]
asyncio.run(sync_all_devices(device_ids))

Important Notes

  • Server Time Source: The device is synchronized to the server’s local time, not UTC. Ensure your server’s clock is accurate.
  • Timezone Awareness: The device will use its own timezone settings. If you need UTC timestamps, configure the device’s timezone accordingly.
  • Attendance Impact: Synchronization does not affect existing attendance records, only future ones.
  • Thread Safety: The operation uses device-specific locks to prevent concurrent modifications.
  • No Downtime: The device remains operational during synchronization.

When to Sync

You should synchronize device time:
  • After device installation: Ensure correct time from the start
  • After power outages: Devices may lose time during extended outages
  • Periodically: Schedule daily or weekly syncs to prevent drift
  • Before audits: Ensure accurate timestamps for compliance
  • After daylight saving changes: If applicable in your region

Troubleshooting

Sync Fails Repeatedly

  1. Check network connectivity with the ping endpoint
  2. Verify device is powered on and responsive
  3. Check for firewall rules blocking communication
  4. Ensure device password is correct in the device configuration

Time Drifts Quickly

If the device time drifts significantly between syncs:
  • The device’s internal clock battery may need replacement
  • Network latency may be high (affects sync accuracy)
  • Consider more frequent synchronization (e.g., every 6 hours)

Build docs developers (and LLMs) love