updaterthread.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include "updaterthread.h"
  2. #include "qapplication.h"
  3. #include "qdir.h"
  4. #include <QEventLoop>
  5. #include <QNetworkAccessManager>
  6. #include <QNetworkReply>
  7. #include <QProcess>
  8. #include <QElapsedTimer>
  9. bool isNetworkAvailable()
  10. {
  11. QNetworkAccessManager manager;
  12. QEventLoop loop;
  13. // 进行一个简单的GET请求
  14. QNetworkReply *reply = manager.get(QNetworkRequest(QUrl("http://ver.stem993.cn/ping")));
  15. // 等待直到请求完成
  16. QObject::connect(reply, &QNetworkReply::finished, [&]() { loop.quit(); });
  17. loop.exec(); // 事件循环
  18. // 检查请求是否成功
  19. bool success = reply->error() == QNetworkReply::NoError;
  20. QString response = reply->readAll();
  21. reply->deleteLater(); // 清理
  22. return success && response == "OK";
  23. }
  24. bool updateServer()
  25. {
  26. return true;
  27. }
  28. bool runUpdate()
  29. {
  30. const QString app_version = qApp->applicationVersion();
  31. const QString pid = QString::number(qApp->applicationPid());
  32. QStringList arg;
  33. arg << app_version << pid << "http://ver.stem993.cn/api/v1/sys/ver/check_for_update";
  34. arg << qApp->applicationFilePath();
  35. const QString program = qApp->applicationDirPath() + "/../updater.exe";
  36. bool isrun = QProcess::startDetached(program, arg);
  37. if (isrun == false) {
  38. // 这里主要是为了 收集错误信息 运行肯定是运行不了的
  39. QProcess process;
  40. process.start(program, arg);
  41. if (!process.waitForStarted()) {
  42. qDebug() << "Error: Process failed to start.";
  43. qDebug() << "Error String:" << process.errorString();
  44. return false;
  45. }
  46. // 如果需要,可以连接信号以获取标准输出和标准错误
  47. QObject::connect(&process, &QProcess::readyReadStandardOutput, [&]() {
  48. qDebug() << "Output:" << process.readAllStandardOutput();
  49. });
  50. QObject::connect(&process, &QProcess::readyReadStandardError, [&]() {
  51. qDebug() << "Error:" << process.readAllStandardError();
  52. });
  53. // 等待进程结束
  54. process.waitForFinished();
  55. }
  56. return isrun;
  57. }
  58. UpdaterThread::UpdaterThread(QObject *parent)
  59. : QThread(parent)
  60. {}
  61. void UpdaterThread::run()
  62. {
  63. // 首先执行一次
  64. if (isNetworkAvailable()) {
  65. if (runUpdate()) {
  66. }
  67. updateServer();
  68. }
  69. QElapsedTimer timer; // 创建高精度计时器
  70. timer.start(); // 启动计时器
  71. while (true) {
  72. // 校验网络
  73. if (timer.elapsed() >= 3600000) { // 检查是否经过1小时(3600000毫秒)
  74. timer.restart(); // 重新启动计时器
  75. if (isNetworkAvailable()) {
  76. if (runUpdate()) {
  77. }
  78. updateServer();
  79. }
  80. }
  81. msleep(1000); // 休息1秒
  82. }
  83. }