A job system for Swift backends.

Overview

Jobs

Language Build Status codecov codebeat badge GitHub license

A minimalistic job system in Swift, for Swift

Table of Contents

Integration

Update your Package.swift file.

.package(url: "https://github.com/BrettRToomey/Jobs.git", from: "1.1.1")

Getting started ๐Ÿš€

Creating a new Job is as simple as:

Jobs.add(interval: .seconds(4)) {
    print("๐Ÿ‘‹ I'm printed every 4 seconds!")
}

Intervals โฒ

The Duration enumeration currently supports .seconds, hours, .days and .weeks.

Jobs.add(interval: .days(5)) {
    print("See you every 5 days.")
}

Syntax candy ๐Ÿญ

It's possible to create a Duration from an Int and a Double.

10.seconds // `Duration.seconds(10)`
4.hours // `Duration.hours(4)`
2.days // `Duration.days(2)`
3.weeks // `Duration.weeks(3)`

Starting a job ๐ŸŽฌ

By default, Jobs are started automatically, but if you wish to start one yourself, even at a later point in time, just do the following:

let job = Jobs.add(interval: 2.seconds, autoStart: false) {
    print("I wasn't started right away.")
}
//...
job.start()

Stopping a job โœ‹

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.

Jobs.oneoff {
    print("Sadly, I'm not a phoenix.")            
}

How about waiting a little?

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.

Jobs.add(
    interval: 10.seconds,
    action: {
        throw Error.someError
    },
    onError: { error in
        print("caught an error: \(error)")
        return RecoverStrategy.default
    }
)

Retry on failure โญ•๏ธ

By default, jobs will be attempted again after a five second delay. If you wish to override this behavior you must first implement an onError handler and return one of the following RecoveryStrategy cases.

.none //do not retry
.default //retry after 5 seconds
.retry(after: Duration) //retry after specified duration

Here's a small sample:

enum Error: Swift.Error {
  case recoverable
  case abort
}

Jobs.add(
    interval: 1.days,
    action: {
        //...
    },
    onError: { error in
        switch error {
        //we cannot recover from this
        case .abort:
            //do not retry
            return .none

        //we can recover from this
        case .recoverable:
            //... recovery code

            //try again in 15 seconds
            return .retry(after: 15.seconds)
        }
    }
)
Comments
  • Vapor + Jobs error on multiple JSONs

    Vapor + Jobs error on multiple JSONs

    Hi, I would like to use Jobs, however when I use this:

    dependencies: [
            .Package(url: "https://github.com/vapor/vapor", majorVersion: 1, minor: 2),
            .Package(url: "https://github.com/BrettRToomey/Jobs.git", majorVersion: 0)
        ]
    

    I get this from running vapor xcode

    No Packages folder, fetch may take a while...
    Fetching Dependencies [Failed]
    Error: swift-package: error: multiple modules with the name JSON found
    fix: modules should have a unique name across dependencies
    

    I know you are using different JSON parser than Vapor, so how can I work around this name duplication?

    opened by syky27 7
  • Can this be the queue package Vapor is missing?

    Can this be the queue package Vapor is missing?

    I just saw this the other day And it's one of the things I talked with tanner & logan about.

    In php we had a queue system https://laravel.com/docs/5.3/queues

    But that was cause how php runs (request based)

    With Vapor we have a runtime so this load can be done on the webservers

    One feature (from doc) which is missing, is just firering a job once as an "async task" this can be useful for low response time apis.

    Is this something this package can do?

    Also thinking even further Moving the load away from webservers to another server (like the laravel queues system) can be very useful. and having it running as a queue with workers is a good way to deal high load.

    Just wanted to open a discussion. If you see this package can be that one day or it should be another package?

    Awesome work btw!

    // Casper

    question 
    opened by Casperhr 5
  • Failed to build on Ubuntu 16.04

    Failed to build on Ubuntu 16.04

    Hello! I'm trying to build project with "Jobs" package on my DigitalOcean droplet (Ubuntu 16.04). And I'm getting this errors:

    .build/checkouts/Jobs.git--5850231031452440998/Sources/Jobs.swift:269:5: warning: @discardableResult declared on a function returning Void is unnecessary static func schedule(

    .build/checkouts/Jobs.git--5850231031452440998/Sources/Jobs.swift:279:12: warning: @discardableResult declared on a function returning Void is unnecessary public static func schedule(

    .build/checkouts/Jobs.git--5850231031452440998/Sources/Jobs.swift:289:5: warning: @discardableResult declared on a function returning Void is unnecessary static func schedule(

    .build/checkouts/Jobs.git--5850231031452440998/Sources/Shell.swift:8:25: error: use of undeclared type 'Task' typealias Process = Task

    opened by yura-voevodin 4
  • Added support for specifying duration in hours

    Added support for specifying duration in hours

    I often want to dispatch jobs every other hour or similar. Would be nice with support for specifying the intervals/duration in hours.

    Let me know if you need any changes to this.

    opened by ksmandersen 1
  • How to resolve an error: 'seconds' is inaccessible due to 'internal' protection level?

    How to resolve an error: 'seconds' is inaccessible due to 'internal' protection level?

    When I try to call

    Jobs.oneoff(delay: 10.seconds) { }

    it shows an error:

    'seconds' is inaccessible due to 'internal' protection level

    How to resolve this?

    opened by joe528 1
  • Disabled JSON

    Disabled JSON

    People are having conflicts with Vapor's definition of JSON and vdka's. I'll just disable the import until JSON is done and I can get one/both of the packages to rename.

    opened by BrettRToomey 1
  • Update for Swift 4.2

    Update for Swift 4.2

    Using isEmpty seemed like the easiest way to retain backwards compatibility. Since this change will require a version change, should I update the README as well or will that be done in a release commit?

    opened by jmousseau 0
  • Recovery system and code cleanup

    Recovery system and code cleanup

    A more user-friendly way of handling errors and recoveries. Users can now run the error through a switch and recover differently based on the severity of the error.

    enhancement 
    opened by BrettRToomey 0
  • Cancel a previously created job

    Cancel a previously created job

    Is there a way I can cancel a previous job by name? I want to schedule a job based on a user's input for a specific date, but they have the ability to update the date later on. Therefore I would need to cancel the previous job for that item and add a new one, or update the date of the current job.

    opened by MaherKSantina 0
  • Request: minutes

    Request: minutes

    I often find myself wanting to schedule jobs to run every X minutes. It would be nice to have a .minutes option instead of having to do (X*60).seconds.

    opened by kgn 0
  • Use of unresolved identifier 'Process'

    Use of unresolved identifier 'Process'

    Hi Guys,

    I'm getting an error Use of unresolved identifier 'Process' What this renamed in swift 4? I see that you guys are using swift 4 in some commits but I'm still getting this error.

    Thanks!

    opened by cyberdude 1
Releases(1.1.2)
Owner
Brett R. Toomey
Brett R. Toomey
PillowTalk - An iOS & SwiftUI server monitor tool for linux based machines using remote proc file system with script execution.

An iOS & SwiftUI server monitor tool for linux based machines using remote proc file system with script execution.

Lakr Aream 416 Dec 16, 2022
Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and moreโ€ฆ)

Perfect: Server-Side Swift ็ฎ€ไฝ“ไธญๆ–‡ Perfect: Server-Side Swift Perfect is a complete and powerful toolbox, framework, and application server for Linux, iO

PerfectlySoft Inc. 13.9k Dec 29, 2022
Swift Express is a simple, yet unopinionated web application server written in Swift

Documentation <h5 align="right"><a href="http://demo.swiftexpress.io/">Live ?? server running Demo <img src="https://cdn0.iconfinder.com/data/icons/

Crossroad Labs 850 Dec 2, 2022
Swift backend / server framework (Pure Swift, Supports Linux)

NetworkObjects NetworkObjects is a #PureSwift backend. This framework compiles for OS X, iOS and Linux and serves as the foundation for building power

Alsey Coleman Miller 258 Oct 6, 2022
Simple server APIs in Swift

Simple server APIs in Swift

null 4 Apr 25, 2022
A dockerized microservice written in Swift using Vapor.

price-calculation-service-swift This is an example project for a university project. It uses Vapor to serve a microservice written in Swift. The point

Fabian Geistert 1 Aug 23, 2022
Tiny http server engine written in Swift programming language.

What is Swifter? Tiny http server engine written in Swift programming language. Branches * stable - lands on CocoaPods and others. Supports the latest

null 3.6k Dec 31, 2022
Swift HTTP server using the pre-fork worker model

Curassow Curassow is a Swift Nest HTTP Server. It uses the pre-fork worker model and it's similar to Python's Gunicorn and Ruby's Unicorn. It exposes

Kyle Fuller Archive 397 Oct 30, 2022
Lightweight library for web server applications in Swift on macOS and Linux powered by coroutines.

Why Zewo? โ€ข Support โ€ข Community โ€ข Contributing Zewo Zewo is a lightweight library for web applications in Swift. What sets Zewo apart? Zewo is not a w

Zewo 1.9k Dec 22, 2022
๐Ÿ’ง A server-side Swift HTTP web framework.

Vapor is an HTTP web framework for Swift. It provides a beautifully expressive and easy-to-use foundation for your next website, API, or cloud project

Vapor 22.4k Jan 3, 2023
Sinatra-like DSL for developing web apps in Swift

Swiftra Swiftra is a library that provides DSLs like Sinatra. System Requirements DEVELOPMENT-SNAPSHOT-2016-02-08-a Example See swiftra-example. impor

Shun Takebayashi 262 Jun 29, 2022
A minimal, fast and unopinionated web framework for Swift

![Fire Image] (http://i.imgur.com/1qR6Nl4.png) Blackfire An extremely fast Swift web framework ?? Getting Started If you're familiar with express.js t

Elliott Minns 908 Dec 2, 2022
HTTP Implementation for Swift on Linux and Mac OS X

Swift HTTP Server Simple HTTP implementation for Swift using POSIX socket API. Running on Mac OS X and Linux. For Mac users: You can install new Swift

Huy 451 Jul 28, 2022
libuv base Swift web HTTP server framework

Notice Trevi now open a Trevi Community. Yoseob/Trevi project split up into respective Trevi, lime, middlewares and sys packages at our community. If

leeyoseob 46 Jan 29, 2022
A lightweight library for writing HTTP web servers with Swift

Taylor Disclaimer: Not actively working on it anymore. You can check out some alternatives Swift 2.0 required. Working with Xcode 7.1. Disclaimer: It

Jorge Izquierdo 925 Nov 17, 2022
Frank is a DSL for quickly writing web applications in Swift

Frank Frank is a DSL for quickly writing web applications in Swift with type-safe path routing. Sources/main.swift import Frank // Handle GET request

Kyle Fuller Archive 376 Jan 3, 2023
A Swift web framework and HTTP server.

A Swift Web Framework and HTTP Server Summary Kitura is a web framework and web server that is created for web services written in Swift. For more inf

Kitura 7.6k Dec 27, 2022
A Ruby on Rails inspired Web Framework for Swift that runs on Linux and OS X

IMPORTANT! We don't see any way how to make web development as great as Ruby on Rails or Django with a very static nature of current Swift. We hope th

Saulius Grigaitis 2k Dec 5, 2022
High Performance (nearly)100% Swift Web server supporting dynamic content.

Dynamo - Dynamic Swift Web Server Starting this project the intention was to code the simplest possible Web Server entirely in Swift. Unfortunately I

John Holdsworth 68 Jul 25, 2022