Skip to content

Commit

Permalink
Merge pull request #24 from BrettRToomey/scheduled-jobs
Browse files Browse the repository at this point in the history
One-off jobs
  • Loading branch information
BrettRToomey committed Jan 18, 2017
2 parents 1a3d6c7 + 3c03f2e commit 1e0a974
Show file tree
Hide file tree
Showing 4 changed files with 151 additions and 34 deletions.
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Jobs
[![Language](https://img.shields.io/badge/Swift-3-brightgreen.svg)](http://swift.org) ![Build Status](https://travis-ci.org/BrettRToomey/Jobs.svg?branch=master)
[![codecov](https://codecov.io/gh/BrettRToomey/Jobs/branch/master/graph/badge.svg)](https://codecov.io/gh/BrettRToomey/Jobs)
[![codebeat badge](https://codebeat.co/badges/1a9e0ad5-33d5-4bbc-a229-1691250f69d3)](https://codebeat.co/projects/github-com-brettrtoomey-jobs)
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/BrettRToomey/Jobs/master/LICENSE.md)

A minimalistic job system in Swift, for Swift
Expand All @@ -24,7 +25,7 @@ Update your `Package.swift` file.
Creating a new `Job` is as simple as:
```swift
Jobs.add(interval: .seconds(4)) {
print("👋 I'm printed 4 times!")
print("👋 I'm printed every 4 seconds!")
}
```

Expand Down Expand Up @@ -59,6 +60,21 @@ Giving up has never been so easy!
job.stop()
```

## One-off jobs
If you just want to asynchronously run a job, but not repeat it you can use the `oneoff` functions.
```swift
Jobs.oneoff {
print("Sadly, I'm not a phoenix.")
}
```

How about waiting a little?
```swift
Jobs.oneoff(delay: 10.seconds) {
print("I was delayed by 10 seconds.")
}
```

## Error handling ❌
Sometimes jobs can fail, that's okay, we have you covered.
```swift
Expand Down
26 changes: 26 additions & 0 deletions Sources/Day.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
public enum Day: Int {
case today
case sunday
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
}

extension Day: Comparable {
public static func <(lhs: Day, rhs: Day) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}

extension Day: Strideable {
public func advanced(by n: Int) -> Day {
return Day(rawValue: rawValue + n) ?? .sunday
}

public func distance(to other: Day) -> Int {
return other.rawValue - self.rawValue
}
}
30 changes: 4 additions & 26 deletions Sources/Helpers.swift
Original file line number Diff line number Diff line change
@@ -1,35 +1,13 @@
import Foundation
/*import JSON

//TODO(Brett): change implementation to C since foundation is broken on Linux
func parseJSONFile(path: String) throws -> JSON {
let fileString = try String(contentsOfFile: path)
let json = try JSON.Parser.parse(
fileString,
options: [.allowComments, .omitNulls]
)
return json
}*/

public enum Day: Int {
case today
case sunday
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
}

typealias Time = (hour: Int, minute: Int)
public typealias Time = (hour: Int, minute: Int)

extension Int {
var am: Time {
public var am: Time {
return (hour: self, minute: 0)
}

var pm: Time {
public var pm: Time {
guard self <= 12 && self != 0 else {
return (hour: self, minute: 0)
}
Expand All @@ -39,7 +17,7 @@ extension Int {
}

extension Date {
static func today() -> (Day?, Int?, Int?) {
static func now() -> (Day?, Int?, Int?) {
let components = Calendar(identifier: .gregorian).dateComponents([.weekday, .hour, .minute], from: Date())

guard
Expand Down
111 changes: 104 additions & 7 deletions Sources/Jobs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -178,15 +178,15 @@ public final class Jobs {
}

/**
Registers a new `Job` with the provided properties.
Registers a new `Job` with the provided properties.
- Parameters:
- name: The name of the job.
- interval: How often the job is performed.
- autoStart: Whether or not to start the job automatically.
- action: The action to perform.
- Parameters:
- name: The name of the job.
- interval: How often the job is performed.
- autoStart: Whether or not to start the job automatically.
- action: The action to perform.
- Returns: The instantiated `Job`.
- Returns: The instantiated `Job`.
*/
@discardableResult
public static func add(
Expand All @@ -203,7 +203,104 @@ public final class Jobs {
onError: nil
)
}

@discardableResult
public static func delay(
name: String? = nil,
by deadline: Duration,
interval: Duration,
action: @escaping Job.Action,
onError errorCallback: Job.ErrorCallback? = nil
) -> Job {
let job = Job(
name: name,
interval: interval.unixTime,
action: action,
errorCallback: errorCallback
)

job.isRunning = true
shared.queue(job, in: deadline)

return job
}

@discardableResult
public static func delay(
name: String? = nil,
by deadline: Duration,
interval: Duration,
action: @escaping Job.Action
) -> Job {
return delay(
name: name,
by: deadline,
interval: interval,
action: action,
onError: nil
)
}

public static func oneoff(
delay: Duration = 0.seconds,
action: @escaping Job.Action
) {
oneoff(delay: delay, action: action, onError: nil)
}

public static func oneoff(
delay: Duration = 0.seconds,
action: @escaping Job.Action,
onError errorHandler: ((Error) -> Void)?
) {
let workItem = DispatchWorkItem {
do {
try action()
} catch {
errorHandler?(error)
}
}

shared.queue(workItem, deadline: delay)
}

//TODO(Brett):
@discardableResult
static func schedule(
_ days: Set<Day>,
at: Time,
action: @escaping Job.Action
) {

}

//TODO(Brett):
@discardableResult
public static func schedule(
_ days: CountableRange<Day>,
at: Time,
action: @escaping Job.Action
) {

}

//TODO(Brett):
@discardableResult
static func schedule(
_ days: CountableClosedRange<Day>,
at: Time,
action: @escaping Job.Action
) {

}

func queue(_ dispatchItem: DispatchWorkItem, deadline: Duration) {
let deadline: DispatchTime = .now() + deadline.unixTime
lock.locked {
workerQueue.asyncAfter(deadline: deadline, execute: dispatchItem)
}
}

func queue(_ job: Performable, in deadline: Duration) {
let deadline: DispatchTime = .now() + deadline.unixTime
lock.locked {
Expand Down

0 comments on commit 1e0a974

Please sign in to comment.