Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions .github/workflows/swiftpm.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: SwiftPM

on:
pull_request:
branches: [master]
push:
branches: [master]

permissions:
contents: read

concurrency:
group: swiftpm-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true

jobs:
macos:
name: macOS debug and release tests
runs-on: macos-15
timeout-minutes: 15
steps:
- name: Check out source
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- name: Show Swift version
run: swift --version
- name: Test debug build
run: swift test --jobs 2
- name: Test release build
run: swift test --configuration release --jobs 2
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ playground.xcworkspace
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
# Packages/
.build/
.swiftpm/

# CocoaPods
#
Expand All @@ -66,4 +67,4 @@ Carthage/Build
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/test_output
34 changes: 34 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// swift-tools-version:5.0

import PackageDescription

let package = Package(
name: "SwiftTimer",
platforms: [
.iOS(.v8),
.macOS(.v10_11),
.tvOS(.v10),
.watchOS(.v3)
],
products: [
.library(name: "SwiftTimer", targets: ["SwiftTimer"])
],
targets: [
.target(
name: "SwiftTimer",
path: "Sources",
exclude: [
"Info-iOS.plist",
"Info-macOS.plist",
"Info-tvOS.plist",
"Info-watchOS.plist",
"SwiftTimer.h"
]
),
.testTarget(
name: "SwiftTimerTests",
dependencies: ["SwiftTimer"]
)
],
swiftLanguageVersions: [.v5]
)
56 changes: 55 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,62 @@ timer.start()

## Installation

Carthage:
### Swift Package Manager

SwiftTimer can be added as a Swift Package Manager dependency with Swift 5.0 or later.
The package exposes the `SwiftTimer` library and keeps the existing deployment targets:
iOS 8, macOS 10.11, tvOS 10, and watchOS 3. Your Xcode version may require a newer
deployment target. The package also builds on Linux using Foundation and Dispatch.

In Xcode, choose **File > Add Package Dependencies**, enter
`https://github.com/100mango/SwiftTimer.git`, and add the `SwiftTimer` product to your target.
Select **Up to Next Major Version** starting at **1.2.0**. Version 1.2.0 is the
first release with a package manifest; the older `v1.0` and `1.1` tags do not
support Swift Package Manager.

For a `Package.swift` dependency:

~~~swift
dependencies: [
.package(url: "https://github.com/100mango/SwiftTimer.git", from: "1.2.0")
],
targets: [
.target(name: "YourTarget", dependencies: ["SwiftTimer"])
]
~~~

Then use `import SwiftTimer` in your Swift files. The package compiles in Swift 5
language mode, including when used with a Swift 6 toolchain.

### Queue and cancellation behavior

Use each timer instance from a single serial queue. `fire()` calls its handler
synchronously on the caller's queue; scheduled events use the queue passed to the
initializer. Keep a strong reference to a timer for as long as it is needed.

Debounce and throttle registration and cancellation are safe to call concurrently.
Identifiers share one registry across both operations. A pending throttle ignores
the same identifier; debounce replaces any pending work with that identifier.
The identifier becomes available before its handler runs, so handlers may schedule
or cancel new work with the same identifier. Cancellation prevents pending work
from starting; it does not interrupt a handler that has already started.

### Carthage

~~~
github "100mango/SwiftTimer"
~~~

## Testing

Run the cross-platform package tests with a current Swift toolchain:

~~~sh
swift test
swift test -c release
~~~

The package tests cover timers, countdowns, debounce, and throttle without UIKit,
including lifecycle, reentrant handlers, concurrent cancellation, and input boundaries.
The existing Xcode project and its iOS tests remain available for Apple-platform
validation; Linux package tests do not replace Apple SDK or device testing.
69 changes: 39 additions & 30 deletions Sources/SwiftTimer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//

import Foundation
import Dispatch

public class SwiftTimer {

Expand Down Expand Up @@ -92,52 +93,60 @@ public class SwiftTimer {
//MARK: Throttle
public extension SwiftTimer {

private static var workItems = [String:DispatchWorkItem]()
private static var workItems = [String: (item: DispatchWorkItem, token: UUID)]()
private static let workItemsLock = NSLock()

///The Handler will be called after interval you specified
///Calling again in the interval cancels the previous call
static func debounce(interval: DispatchTimeInterval, identifier: String, queue: DispatchQueue = .main , handler: @escaping () -> Void ) {

//if already exist
if let item = workItems[identifier] {
item.cancel()
}

let item = DispatchWorkItem {
handler();
workItems.removeValue(forKey: identifier)
};
workItems[identifier] = item
queue.asyncAfter(deadline: .now() + interval, execute: item);
scheduleWork(interval: interval, identifier: identifier, queue: queue, replacing: true, handler: handler)
}

///The Handler will be called after interval you specified
///It is invalid to call again in the interval
static func throttle(interval: DispatchTimeInterval, identifier: String, queue: DispatchQueue = .main , handler: @escaping () -> Void ) {

//if already exist
if workItems[identifier] != nil {
return;
}

let item = DispatchWorkItem {
handler();
workItems.removeValue(forKey: identifier)
};
workItems[identifier] = item
queue.asyncAfter(deadline: .now() + interval, execute: item);

scheduleWork(interval: interval, identifier: identifier, queue: queue, replacing: false, handler: handler)
}

static func cancelThrottlingTimer(identifier: String) {
if let item = workItems[identifier] {
item.cancel()
workItems.removeValue(forKey: identifier)
workItemsLock.lock()
let pending = workItems.removeValue(forKey: identifier)
workItemsLock.unlock()
pending?.item.cancel()
}

private static func scheduleWork(interval: DispatchTimeInterval, identifier: String, queue: DispatchQueue, replacing: Bool, handler: @escaping () -> Void) {
workItemsLock.lock()
let previous = workItems[identifier]
if previous != nil && !replacing {
workItemsLock.unlock()
return
}

let token = UUID()
let item = DispatchWorkItem {
workItemsLock.lock()
guard workItems[identifier]?.token == token else {
workItemsLock.unlock()
return
}
// Remove only this generation before invoking user code. A handler may
// immediately schedule or cancel work with the same identifier.
let pending = workItems.removeValue(forKey: identifier)
workItemsLock.unlock()
withExtendedLifetime(pending) {
handler()
}
}
workItems[identifier] = (item, token)
workItemsLock.unlock()
// Keep replaced captures alive until after unlocking; their deinitializers
// may themselves register or cancel work.
previous?.item.cancel()
queue.asyncAfter(deadline: .now() + interval, execute: item)
}



}

//MARK: Count Down
Expand Down
Loading
Loading