利用控制台下定时器定时关机代码示例

本文详细介绍了如何使用srvany将一个控制台应用程序转换为Windows服务,并实现定时关机的功能。通过配置服务启动时间和参数,使得系统能够在指定的时间自动关闭。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 定时关机,用srvany安装成服务使用。



示例代码工程,基于vs2010
/Files/alantop/shutoff.rar


//  shutoff.cpp : 定义控制台应用程序的入口点。
//

#include 
" stdafx.h "
#include 
< atltime.h >
#include 
< windows.h >  
#include 
< stdio.h >  
#include 
< conio.h >  

void  shutdown()
{
    
// 从config中读取关机参数

    CString cs 
=    " shutoff " ;
    CString hour 
=   " hour " ;
    CString filename 
=   " .\\config.ini " ;
    
int  offHour  = ::GetPrivateProfileInt(cs,hour, 0 ,filename);
    CString min 
=   " min " ;
    
int  offMin  =  ::GetPrivateProfileInt(cs,min, 0 ,filename);

    
// 判断时间并关机

    CTime t
= CTime::GetCurrentTime(); 
    CTime t1(t.GetYear(),t.GetMonth(),t.GetDay(),offHour,offMin,t.GetSecond());
    CTimeSpan ts 
=  t1  -  t;

    printf(
" 还有%d小时%d分钟关机.\n " , ts.GetHours(),ts.GetMinutes() );

    
int  nHour  =  t.GetHour();
    
int  nMin  =  t.GetMinute();

    
char  command[]  = " c:\\windows\\system32\\shutdown.exe -s -t 60 " ;
    
if  (nHour  ==  offHour  &&  nMin  ==  nHour)
        system(command);
}

VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime) 

    
// printf("定时器函数开始工作\n"); 
    shutdown();


DWORD CALLBACK Thread(PVOID pvoid)    
{   
    BOOL  bRet; 
    MSG  msg; 
    PeekMessage(
& msg,NULL,WM_USER,WM_USER,PM_NOREMOVE); 

    UINT  timerid
= ::SetTimer(NULL, 111 , 10000 ,TimerProc); 
    
while  ((bRet  =  GetMessage( & msg,NULL, 0 , 0 )) != 0 )   
    {     
        
if  (bRet ==- 1
        { 
            
//    handle   the   error   and   possibly   exit   
        }   
        
else  
        { 
            TranslateMessage(
& msg);     
            DispatchMessage(
& msg);     
        } 
    } 
    KillTimer(NULL,timerid);   
    printf(
" 线程函数结束\n "  ); 
    
return   0



int  _tmain( int  argc, _TCHAR *  argv[])
{
    CString cs 
=    " shutoff " ;
    CString hour 
=   " hour " ;
    CString filename 
=   " .\\config.ini " ;
    
int  offHour  = ::GetPrivateProfileInt(cs,hour, 0 ,filename);
    CString min 
=   " min " ;
    
int  offMin  =  ::GetPrivateProfileInt(cs,min, 0 ,filename);

    DWORD   dwThreadId;   
    printf(
" 定时关机程序启动,计算机将在%d小时%d关机。\n " ,offHour, offMin );   
    HANDLE hThread 
=  CreateThread(NULL, 0 ,Thread, 0 , 0 , & dwThreadId); 
    _getch();
    
return   0 ;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值