Skip to content

Instantly share code, notes, and snippets.

@DivineDominion
Created November 4, 2022 08:11
Show Gist options
  • Save DivineDominion/98f612ced11fdb61ecbf24c7c4c177e8 to your computer and use it in GitHub Desktop.
Save DivineDominion/98f612ced11fdb61ecbf24c7c4c177e8 to your computer and use it in GitHub Desktop.
Jiggle thread implementation in Swift
// Based on an idea from page 188 in:
//
// Robert C. Martin (2009):
// "Clean Code. A Handbook of Agile Software Craftsmanship",
// Upper Saddle River: Prentice Hall.
import Foundation
@inline(__always)
func jiggleThread(minimumDelay: TimeInterval = 0.3, maximumDelay: TimeInterval = 4) {
#if DEBUG
if isRunningTests { return }
let randomRange: TimeInterval = (maximumDelay - minimumDelay) * TimeInterval(10)
let randomInterval: TimeInterval = TimeInterval(arc4random_uniform(UInt32(randomRange)))
let seconds: TimeInterval = minimumDelay + (randomInterval * 0.1)
log.verbose("Thread \"\(Thread.current.description)\" sleeps for \(seconds)s")
Thread.sleep(forTimeInterval: seconds)
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment