import VaporCron
let job = try app.cron.schedule("* * * * *") { // or add one more * to launch every second
print("Closure fired")
}
Complex job in dedicated struct
import Vapor
import VaporCron
/// Your job should conform to `VaporCronSchedulable` or `VaporCronInstanceSchedulable`
struct ComplexJob: VaporCronSchedulable {
static var expression: String { "* * * * *" } // or add one more * to launch every second
static func task(on application: Application) -> EventLoopFuture<Void> {
return application.eventLoopGroup.future().always { _ in
print("ComplexJob fired")
}
}
}
let complexJob = try app.cron.schedule(ComplexJob.self)
struct ComplexInstanceJob: VaporCronInstanceSchedulable {
static var expression: String { "* * * * *" } // or add one more * to launch every second
private let application: Application
init(application: Application) {
self.application = application
}
func task() -> EventLoopFuture<Void> {
return application.eventLoopGroup.future().always { _ in
print("ComplexJob fired")
}
}
}
let complexInstanceJob = try app.cron.schedule(ComplexInstanceJob.self)
💡you also could call `req.cron.schedule(…)``
💡💡Scheduled job may be cancelled just by calling .cancel()
Concurrency (swift>=5.5)
use AsyncVaporCronSchedulable instead VaporCronSchedulable
use AsyncVaporCronInstanceSchedulable instead VaporCronInstanceSchedulable
public struct TestCron: AsyncVaporCronSchedulable {
public typealias T = Void
public static var expression: String {
"*/1 * * * *" // or add one more * to launch every 1st second
}
public static func task(on application: Application) async throws -> Void {
application.logger.info("\(Self.self) is running...")
}
}
Where to define
On boot
You could define all cron jobs in your boot.swift cause here is app: Application which contains eventLoop
import Vapor
import VaporCron
// Called before your application initializes.
func configure(_ app: Application) throws {
let complexJob = try app.cron.schedule(ComplexJob.self)
/// This example code will cancel scheduled job after 120 seconds
/// so in a console you'll see "Closure fired" three times only
app.eventLoopGroup.next().scheduleTask(in: .seconds(120)) {
complexJob.cancel()
}
}
In request handler
Some jobs you may want to schedule from some request handler like this
Support this lib by giving a ⭐️
Built for Vapor4
How to install
Swift Package Manager
In your target’s dependencies add
"VaporCron"
e.g. like this:Usage
Simple job with closure
Complex job in dedicated struct
Concurrency (swift>=5.5)
use
AsyncVaporCronSchedulable
insteadVaporCronSchedulable
use
AsyncVaporCronInstanceSchedulable
insteadVaporCronInstanceSchedulable
Where to define
On boot
You could define all cron jobs in your
boot.swift
cause here isapp: Application
which containseventLoop
In request handler
Some jobs you may want to schedule from some request handler like this
How to do something in the database every 5 minutes?
Dependencies
Contributing
Please feel free to contribute!