public void Execute(CancellationToken cancellationToken) { foreach (var table in ProcessedTables) { Logger.DebugFormat("Removing outdated records from table '{0}'...", table); int removedCount = 0; do { _storage.UsingDatabase(connection => { if ( connection.DataProvider.GetSchemaProvider() .GetSchema(connection) .Tables.Any(t => t.TableName.ToLowerInvariant() == table.ToLowerInvariant())) { using ( var lck = _storage.GetConnection() .AcquireDistributedLock(DistributedLockKey, DefaultLockTimeout)) { removedCount = connection.Execute( String.Format(@" SET TRANSACTION ISOLATION LEVEL READ COMMITTED; START TRANSACTION; delete from {0}.{1} where ExpireAt < @now limit @count; COMMIT;", connection.DataProvider.GetSchemaProvider().GetSchema(connection).Database, table), new { now = DateTime.UtcNow, count = NumberOfRecordsInSinglePass }); } } }); if (removedCount > 0) { Logger.Trace(String.Format("Removed {0} outdated record(s) from '{1}' table.", removedCount, table)); cancellationToken.WaitHandle.WaitOne(DelayBetweenPasses); cancellationToken.ThrowIfCancellationRequested(); } } while (removedCount != 0); } cancellationToken.WaitHandle.WaitOne(_checkInterval); }