我正在尝试在我的数据库中每分钟安排一个随机元素的查询。
计划部分有效,但我找不到从数据库中选择项目的方法......
我是一个快速的初学者。也许我错过了重要的事情!
如果您需要更多信息,请告诉我
这是我在boot.swift中的代码
import Fluent
import FluentSQLite
func foo(on container: Container) {
let future = container.withPooledConnection(to: .sqlite) { db in
return Future.map(on: container){ }
}
future.do{ msg in
let allQuotes = QuoteOfTheDay.query(on: ).all().wait()
quoteOfTheDay = allQuotes.randomElement()
}.catch{ error in
print("\(error.localizedDescription)")
}
}
/// Called after your application has initialized.
public func boot(_ app: Application) throws {
// your code here
func runRepeatTimer() {
app.eventLoop.scheduleTask(in: TimeAmount.minutes(1), runRepeatTimer)
foo(on: app)
}
runRepeatTimer()
}
Application
符合Container
所以你可以在boot(_:)
中调用它并只提供应用程序
根据您的代码,您可以在启动时通过以下方式查询数据库中的项目:
let req = Request(using: app)
let allQuotes = QuoteOfTheDay.query(on: req).all().wait()
quoteOfTheDay = allQuotes.randomElement()
此外,每24小时您可以使用重复任务。
app.eventLoop.scheduleRepeatedTask(initialDelay: TimeAmount.seconds(0), delay: TimeAmount.hours(24), foo(on: app))