使用C++语言实现修改本地时钟
本文讲解如何使用C++语言实现修改本地时钟
需求
小编开发过程中,遇到一个需要半小时执行一次,连续执行两个月故障的bug。身为一个伟大的程序员,总不能等两个月复现bug吧,于是各路搜索,最后均以失败告终,最后找到类似修改本地时钟的代码库,进行简单编辑,KO!!
源程序
#include <windows.h>
#include <iostream>
#include <chrono>
#include <thread>
bool SetSystemTimeTo(const SYSTEMTIME& newTime) {
// 将SYSTEMTIME转换为FILETIME
FILETIME ft;
if (!SystemTimeToFileTime(const_cast<SYSTEMTIME*>(&newTime), &ft)) {
std::cerr << "SystemTimeToFileTime failed: " << GetLastError() << std::endl;
return false;
}
// 设置系统时钟
if (!SetSystemTime(&newTime)) {
std::cerr << "SetSystemTime failed: " << GetLastError() << std::endl;
return false;
}
return true;
}
void timer_task(SYSTEMTIME &st) {
st.wMonth += (st.wDay+1)/31;
st.wDay=(st.wDay+1)%31;
// 设置时钟
if (SetSystemTimeTo(st)) {
std::cout << "时钟已设置。" << std::endl;
} else {
std::cerr << "时钟设置失败。" << std::endl;
}
}
int main() {
//using namespace std::chrono_literals; // 使用秒的字面量
// 创建新的系统时间结构体
SYSTEMTIME st;
st.wYear = 2024;
st.wMonth = 5;
st.wDay = 0;
st.wHour = 8;
st.wMinute = 0;
st.wSecond = 0;
st.wMilliseconds = 0;
// 计算30秒的时长
std::chrono::milliseconds interval(30000);
// 定义一个无限循环以保持定时器运行
while (true) {
// 执行定时器任务
timer_task(st);
// 休眠指定的时间间隔
std::this_thread::sleep_for(interval);
}
return 0;
}