From 004665e9432c520f4bb25a8140fe986493d78614 Mon Sep 17 00:00:00 2001 From: Albert S Date: Wed, 1 Feb 2023 18:55:13 +0100 Subject: [PATCH] qswiki: Add background worker, currently to clean old sessions mainly --- qswiki.cpp | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/qswiki.cpp b/qswiki.cpp index 4e98669..6be1ce1 100644 --- a/qswiki.cpp +++ b/qswiki.cpp @@ -31,8 +31,8 @@ SOFTWARE. #include "handlers/handlerfactory.h" #include "database/databasefactory.h" #include "config.h" -#include "template.h" #include "session.h" +#include "template.h" #include "logger.h" #include "urlprovider.h" #include "requestworker.h" @@ -74,6 +74,33 @@ std::unique_ptr createCache(const ConfigVariableResolver &resolver) return std::make_unique(path); } +std::thread background_worker; +void start_background_worker(Database &database, Config &config) +{ + background_worker = std::thread( + [&database, &config]() + { + while(true) + { + Logger::log() << "Executing background worker"; + + auto sessionDao = database.createSessionDao(); + auto sessionList = sessionDao->fetch(); + time_t now = time(NULL); + + for(Session &sess : sessionList) + { + if(now - sess.creation_time > config.session_max_lifetime) + { + sessionDao->deleteSession(sess.token); + } + } + + std::this_thread::sleep_for(std::chrono::hours(1)); + } + }); +} + int main(int argc, char **argv) { @@ -136,6 +163,7 @@ int main(int argc, char **argv) Logger::setStream(&logstream); auto database = createDatabase(config); + std::string socketPath = config.configVarResolver.getConfig("socketpath"); CLIHandler cliHandler(config, *database); @@ -158,6 +186,8 @@ int main(int argc, char **argv) exit(EXIT_FAILURE); } + start_background_worker(*database.get(), config); + CLIServer cliServer{cliHandler}; if(!cliServer.detachServer(socketPath)) {