Mihael Isaev

MIT License Swift 5.1 Swift.Stream


别忘了给这个库一个⭐️来支持它哦

为 NIO2 构建

💡NIO1 版本可在 nio1 分支和 1.0.0 标签中找到

如何安装

Swift Package Manager

.package(url: "https://github.com/MihaelIsaev/NIOCronScheduler.git", from:"2.1.0")

在你的 target 依赖中添加 "NIOCronScheduler",例如这样

.target(name: "App", dependencies: ["NIOCronScheduler"]),

用法

import NIOCronScheduler

/// Simplest way is to use closure
let job = try? NIOCronScheduler.schedule("* * * * *", on: eventLoop) { // add one more * to launch every second
    print("Closure fired")
}

/// Or create a struct that conforms to NIOCronSchedulable
struct Job1: NIOCronSchedulable {
    static var expression: String { return "* * * * *" } // add one more * to launch every second

    static func task() {
        print("Job1 fired")
    }
}
let job1 = try? NIOCronScheduler.schedule(Job1.self, on: eventLoop)

/// Or create a struct that conforms to NIOCronFutureSchedulable
/// to be able to return a future
struct Job2: NIOCronFutureSchedulable {
    static var expression: String { return "*/2 * * * *" } // add one more * to launch every 2nd second

    static func task(on eventLoop: EventLoop) -> EventLoopFuture<Void> { //Void is not a requirement, you may return any type
        return eventLoop.newSucceededFuture(result: ()).always {
            print("Job2 fired")
        }
    }
}
let job2 = try? NIOCronScheduler.schedule(Job2.self, on: eventLoop)

可以通过调用 .cancel() 来取消已调度的任务

对于 Vapor 用户

最简单的方法是在 configure.swift 中定义所有的 cron 任务

所以它可能看起来像这样

import Vapor
import NIOCronScheduler

// Called before your application initializes.
func configure(_ app: Application) throws {
    // ...

    let job = try? NIOCronScheduler.schedule("* * * * *", on: app.eventLoopGroup.next()) {
        print("Closure fired")
    }
    /// This example code will cancel scheduled job after 185 seconds
    /// so in a console you'll see "Closure fired" three times only
    app.eventLoopGroup.next().scheduleTask(in: .seconds(185)) {
        job?.cancel()
    }
}

当然,你也可以从 req: Request 中调度一些东西,因为它本身也包含了 eventLoopGroup.next()

限制

Cron 表达式的解析通过 SwifCron 库实现,请阅读它的限制并欢迎为该库做出贡献

贡献

欢迎大家踊跃贡献!