如何在启动时查询数据库?

问题描述 投票:3回答:2

我正在尝试在我的数据库中每分钟安排一个随机元素的查询。

计划部分有效,但我找不到从数据库中选择项目的方法......

我是一个快速的初学者。也许我错过了重要的事情!

如果您需要更多信息,请告诉我

这是我在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()

}


swift vapor
2个回答
1
投票

Application符合Container所以你可以在boot(_:)中调用它并只提供应用程序


0
投票

根据您的代码,您可以在启动时通过以下方式查询数据库中的项目:

          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))
© www.soinside.com 2019 - 2024. All rights reserved.