Skip to content

Instantly share code, notes, and snippets.

@vzsg
Created August 2, 2017 08:22
Show Gist options
  • Save vzsg/4aee17e59cc87f47dbc3bbe49fd1c2f3 to your computer and use it in GitHub Desktop.
Save vzsg/4aee17e59cc87f47dbc3bbe49fd1c2f3 to your computer and use it in GitHub Desktop.
Custom command for daily and weekly tasks for Vapor 2
import FluentProvider
extension Config {
public func setup() throws {
// ...
addConfigurable(command: DailyCommand.init, name: "daily")
}
// ...
}
import Vapor
import Console
import FluentProvider
final class DailyCommand: Command, ConfigInitializable {
var console: ConsoleProtocol
let id = "daily"
let driver: Driver
let log: LogProtocol
required init(config: Config) throws {
console = try config.resolveConsole()
driver = try config.resolveDriver()
log = try config.resolveLog()
}
func run(arguments: [String]) throws {
log.info("Doing daily tasks...")
do {
let newPost = Post(content: "Haha this is a spam post")
try Post.makeQuery(driver).save(newPost)
guard let weekDay = getWeekday() else {
log.warning("Failed to get current weekday!")
return
}
// 0: Sunday
if weekDay == 0 {
log.info("Doing weekly tasks...")
try Post.makeQuery(driver).delete()
} else {
log.info("Skipping weekly tasks...")
}
}
catch {
log.error(error)
}
}
}
private func getWeekday() -> Int? {
var rawTime = time(nil)
guard let timeInfo = localtime(&rawTime) else {
return nil
}
mktime(timeInfo)
return Int(timeInfo.pointee.tm_wday)
}
{
"...": "...",
"//": "Choose which commands this application can run",
"//": "prepare: Supplied by the Fluent provider. Prepares the database (configure in fluent.json)",
"commands": [
"prepare",
"daily"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment