Skip to content

Instantly share code, notes, and snippets.

@Dev1an
Last active May 6, 2019 11:28
Show Gist options
  • Select an option

  • Save Dev1an/06e4bbeb44e0b1b351d5ec3333a361c5 to your computer and use it in GitHub Desktop.

Select an option

Save Dev1an/06e4bbeb44e0b1b351d5ec3333a361c5 to your computer and use it in GitHub Desktop.
Throttle new tasks down when older tasks are still executing.
//
// Throttler.swift
// 3D Viewer
//
// Created by Damiaan on 20/02/2019.
// Copyright © 2019 Devian. All rights reserved.
//
import Dispatch
public class Throttler {
private let group = DispatchGroup()
private let worker = DispatchQueue(label: "Throttle worker", attributes: [])
private let manager = DispatchQueue(label: "Throttle manager", attributes: [])
private var todo: ( () -> Void )?
var notExecuting: Bool { return group.wait(timeout: .now()) == .success }
public func execute(work: @escaping () -> Void) {
manager.sync { todo = work }
if notExecuting {
executeRemainingWork()
}
}
private func executeRemainingWork() {
manager.sync {
group.enter()
if let work = todo {
todo = nil
worker.async {
work()
self.group.leave()
self.executeRemainingWork()
}
} else {
group.leave()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment