Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query database on boot?

Tags:

swift

vapor

I'm trying to schedule the query of a random element every minute in my database.

The schedule part works but I don't find a way to pick an item from the database...

I'm a swift beginner. Maybe I missed something important !

Let me know if you need more informations

This is my code from 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()

}


like image 900
Thomas Schmitt Avatar asked Apr 19 '26 00:04

Thomas Schmitt


1 Answers

Application conforms to Container so you can call it in boot(_:) and just provider the application

like image 78
0xTim Avatar answered Apr 20 '26 14:04

0xTim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!