import type { BackgroundTask } from '../types/index.js';
declare class TasksService {
    private cache;
    private cacheKey;
    private refreshInterval;
    private refreshIntervalId;
    private initialized;
    private shuttingDown;
    private concurrency;
    private runningCount;
    private stallTimeout;
    private redisClient;
    private useTaskRedis;
    private instanceId;
    private lockRenewalInterval;
    private hasInstanceLock;
    private static readonly LOCK_KEY;
    private static readonly LOCK_TTL_SECONDS;
    private static readonly LOCK_RENEWAL_INTERVAL;
    init(): Promise<void>;
    ensureInitialized(): Promise<void>;
    refreshCache(): Promise<void>;
    getNotStartedTasks(): Promise<BackgroundTask[]>;
    /**
     * Atomically claim a task for processing.
     * Uses UPDATE ... WHERE task_status = 'Not started' to prevent duplicate processing.
     * If another worker already claimed the task, returns null (0 rows updated).
     *
     * @param taskId - The task ID to claim
     * @returns The claimed task record, or null if already claimed/not found
     */
    claimTask(taskId: string | number): Promise<BackgroundTask | null>;
    /**
     * Recover tasks stuck in "Running" state beyond the stall timeout.
     * - If retry_count < max_retries: resets to "Not started" for automatic retry
     * - Otherwise: marks as "Error" with stall information
     *
     * Called during initialization and each periodic cache refresh.
     */
    recoverStalledTasks(): Promise<void>;
    /**
     * @deprecated Use tryAcquireLock()/releaseLock() for atomic task coordination.
     * setTaskRunning(true) now delegates to tryAcquireLock() internally.
     */
    setTaskRunning(isRunning: boolean): Promise<void>;
    /**
     * Check if task processing is at capacity.
     * Returns true when running task count >= configured TASK_CONCURRENCY.
     * With default concurrency of 1, returns true if any task is running.
     */
    isTaskRunning(): Promise<boolean>;
    /**
     * Get the number of currently running tasks.
     */
    getRunningCount(): number;
    /**
     * Try to acquire a task processing slot.
     * Respects TASK_CONCURRENCY — allows up to N concurrent tasks per instance.
     * In multi-instance mode, only one instance can hold the processing lock at a time.
     *
     * @param lockTimeout - Redis lock TTL in seconds (multi-instance only, default: 60s)
     * @returns True if slot acquired, false if at capacity or lock held by another instance
     */
    tryAcquireLock(lockTimeout?: number): Promise<boolean>;
    /**
     * Start automatic lock renewal to prevent expiry during long-running tasks.
     * Uses Lua script for atomic check-and-renew (prevents race between GET and EXPIRE).
     */
    private startLockRenewal;
    /**
     * Stop lock renewal interval
     */
    private stopLockRenewal;
    /**
     * Release a task processing slot.
     * When all slots are released, the instance lock (Redis) is also released.
     * @returns True if slot released, false otherwise
     */
    releaseLock(): Promise<boolean>;
    /**
     * In-memory set of job locks held by this instance (single-instance fallback).
     */
    private heldJobLocks;
    /**
     * Acquire a named distributed lock for a scheduled job.
     * Prevents the same job from running on multiple instances simultaneously.
     *
     * - With Redis (`TASK_REDIS_ENABLED=true`): uses `SET NX EX` for cross-instance locking
     * - Without Redis: uses in-memory set (prevents re-entry within same process)
     *
     * @param jobName  - Unique job identifier (e.g., "attendance-cron", "cleanup-job")
     * @param ttlSeconds - Lock TTL in seconds. Should be >= your job's max execution time.
     *                     Lock auto-expires after this, so a crashed instance won't block forever.
     *                     Default: 300 (5 minutes)
     * @returns `true` if lock acquired, `false` if already held (by this or another instance)
     *
     * @example
     * ```ts
     * schedule.scheduleJob(everyFifteenMinutes, async () => {
     *   const locked = await tasksService.acquireJobLock("attendance-cron", 600);
     *   if (!locked) return; // another instance is running this job
     *   try {
     *     await AttendanceUtils.ProcessScheduleAttendance(...);
     *   } finally {
     *     await tasksService.releaseJobLock("attendance-cron");
     *   }
     * });
     * ```
     */
    acquireJobLock(jobName: string, ttlSeconds?: number): Promise<boolean>;
    /**
     * Release a named job lock.
     * Only releases if this instance owns the lock (atomic check via Lua in Redis mode).
     *
     * @param jobName - The job name used in acquireJobLock()
     * @returns `true` if released, `false` if not owned or error
     */
    releaseJobLock(jobName: string): Promise<boolean>;
    startPeriodicRefresh(): void;
    stopPeriodicRefresh(): void;
    /**
     * Add a task to the cached "not started" list without querying the DB.
     * Only adds if the task is "Not started" and scheduled within 4 hours.
     */
    private addTaskToCache;
    /**
     * Remove a task from the cached "not started" list by ID without querying the DB.
     */
    private removeTaskFromCache;
    /**
     * Update a task in the cached "not started" list without querying the DB.
     * Replaces the cached task object with the new document.
     */
    private updateTaskInCache;
    registerHooks(): void;
    /**
     * Wait for all running tasks to complete (with timeout)
     */
    waitForTaskCompletion(timeoutMs?: number): Promise<void>;
    /**
     * Cleanup method for graceful shutdown
     */
    shutdown(timeoutMs?: number): Promise<void>;
    /**
     * Method to manually trigger cache refresh (useful for testing or manual operations)
     */
    forceRefresh(): Promise<void>;
    /**
     * Get cache statistics
     */
    getCacheStats(): Promise<Record<string, any>>;
}
declare global {
    var __baasix_tasksService: TasksService | undefined;
}
declare const tasksService: TasksService;
export default tasksService;
//# sourceMappingURL=TasksService.d.ts.map