使用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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值